Django+SCGI

作者: joliny
发布时间:2015-07-29 11:32:22

Django+SCGI

阿舅于2008-04-21 14:25:18发表

部署了TG,就想着把DJANGO也弄上去。本来是打算用FASTCGI方式的,这个在DJANGO官网上也有教程,但后来又在网上看到了一篇文章,地址如下 http://blog.opensource.org.cn/hdcola/2007/10/django-1.html

这让我立即考虑换成SCGI,本来我的TG也是跑在SCGI上的,既然DJANGO跑在SCGI上性能如此出色,没有不选择它的道理。 更何况用FASTCGI的话配置静态文件的目录必须用REWRITE,ALIAS是无效的 好,启用人肉搜索引擎,终于在一个老外的博客上找到了一篇配置方法, 首先是下载flup和scgi easy_install flup easy_install scgi 新建文件django-scgi.py, 脚本如下: import os import sys

if os.name == 'posix':

    def become_daemon(ourHomeDir='.',outLog='/dev/null',errLog='/dev/null'):         """         Robustly turn us into a UNIX daemon, running in ourHomeDir.         Modelled after the original code of this module and some         sample code from the net.         """

        # first fork         try:             if os.fork() > 0:                 sys.exit(0)     # kill off parent         except OSError, e:             sys.stderr.write("fork #1 failed: (%d) %s" % (e.errno, e.strerror))             sys.exit(1)         os.setsid()         os.chdir(ourHomeDir)         os.umask(0)         # second fork         try:             if os.fork() > 0:                 sys.exit(0)         except OSError, e:             sys.stderr.write("fork #2 failed: (%d) %s" % (e.errno, e.strerror))             sys.exit(1)

        si = open('/dev/null', 'r')         so = open(outLog, 'a+', 0)         se = open(errLog, 'a+', 0)         os.dup2(si.fileno(), sys.stdin.fileno())         os.dup2(so.fileno(), sys.stdout.fileno())         os.dup2(se.fileno(), sys.stderr.fileno())

else:

    def become_daemon(ourHomeDir='.',outLog=None,errLog=None):         """         If we are not running under a POSIX system, just simulate         the daemon mode by doing redirections and directory changeing         """

        os.chdir(ourHomeDir)         os.umask(0)         sys.stdin.close()         sys.stdout.close()         sys.stderr.close()         if errLog and outLog:             sys.stderr=open (errLog, 'a', 0)             sys.stdout=open (outLog, 'a', 0)         elif errLog:             sys.stderr=open (errLog, 'a', 0)             sys.stdout=NullDevice ()         elif outLog:             sys.stdout=open (outLog, 'a', 0)             sys.stderr=NullDevice ()         else:             sys.stdout = NullDevice()             sys.stderr = NullDevice()

    class NullDevice:         """         A substitute for stdout and stderr that writes to nowhere.         This is a substitute for /dev/null         """             def write(self, s):             pass

def main():     from flup.server.scgi_fork import WSGIServer     from django.core.handlers.wsgi import WSGIHandler

    import getopt

    (opts, args) = getopt.getopt(sys.argv[1:], 'f:s:h:p:',         ['settings=','socket=','host=','port=',          'minspare=', 'maxspare=', 'maxchildren=',          'daemon', 'etclog=', 'errorlog=', 'workdir=',          'projects='])         socket = None     host = None     port = None

    minspare = 1     maxspare = 5     maxchildren = 50

    daemon = None     workdir = '.'     etclog = '/dev/null'     errorlog = '/dev/null'

    projects = []

    for (o, v) in opts:         if o in ('-s', '--socket'):             socket = v         elif o in ('-h', '--host'):             host = v         elif o in ('-p', '--port'):             port = int(v)         elif o in ('-f', '--settings'):             os.environ['DJANGO_SETTINGS_MODULE'] = v         elif o in ('--minspare',):             minspare = int(v)         elif o in ('--maxspare',):             maxspare = int(v)         elif o in ('--maxchildren',):             maxchildren = int(v)         elif o in ('--daemon',):             daemon = 1         elif o in ('--errorlog',):             errorlog = v         elif o in ('--etclog',):             etclog = v         elif o in ('--workdir',):             workdir = v         elif o in ('--projects',):             projects.append(v)         # add projects to path     for p in projects:         if p not in sys.path:             sys.path.insert(0, p)

    # if we should run as a daemon, use the above function to turn us     # into one reliably. This should correctly detach from the tty.     if daemon:         become_daemon(ourHomeDir=workdir,             outLog=etclog, errLog=errorlog)

    if socket and not host and not port:         WSGIServer(WSGIHandler(), minSpare=minspare, maxSpare=maxspare, maxChildren=maxchildren, bindAddress=socket).run()     elif not socket and host and port:         WSGIServer(WSGIHandler(), minSpare=minspare, maxSpare=maxspare, maxChildren=maxchildren, bindAddress=(host, port)).run()     else:         print "usage: django-scgi.py [--settings=<settingsmodule>] --socket=<socketname>"         print "   or: django-scgi.py [--settings=<settingsmodule>] --host==<hostname> --port=<portnumber>"         print         print "   additional options are:"         print "      --minspare=<minimum number of spare processes, default 1>"         print "      --maxspare=<maximum number of spare processes, default 5>"         print "      --maxchildren=<maximum number of child processes, default 50>"         print         print "      --daemon"         print "      --etclog=<path for stdout log, default /dev/null>"         print "      --errorlog=<path for stderr log, default /dev/null>"         print "      --workdir=<path for working directory, default .>"         print         print "      --projects=<path to add to sys.path>"

if __name__ == '__main__':

    # first patch our own version of socketpair into the sockets module     # if we don't have it already (comes with Python 2.4)

    import socket     if not hasattr(socket, 'socketpair'):         import eunuchs.socketpair

        def socketpair():             (p,c) = eunuchs.socketpair.socketpair()             (pp,cc) = (socket.fromfd(p,1,1), socket.fromfd(c,1,1))             os.close(c)             os.close(p)             return (pp,cc)

        socket.socketpair = socketpair

    main()

 

OK,将此文件COPY至DJANGO工程文件的上一级路径(和文件夹同一级),然后运行命令 python django-scgi.py --projects=/home/usr/djapp/ --settings=settings --host=localhost --port=8000 wsgi启动了,接下来配置lighttpd scgi.server = ("/" =>                     ("127.0.0.1" =>                          ("host" => "127.0.0.1",                          "port" => 8000,                          "check-local" => "disable")                     )                 )

} 重启lighttpd,OK

 

另外要注意,我用的DJANGO就是目前官网上的0.96版,但其中的wsgi.py(CORE/HANDLERS下)文件是要修改一下的,至少我下载的这个是需要的,官网还没及时补丁 #self.path = environ['PATH_INFO'] #注释掉第77句,然后改成 self.path = force_unicode(environ['SCRIPT_NAME'] + environ['PATH_INFO']) 另外在utils文件夹下还缺少两个文件,分别是encoding.py和safestring.py 去官网上下载 当然,这是我的安装情况,也许你下载的DJANGO不需要这样做

标签: Django Go
来源:http://blog.csdn.net/joliny/article/details/2596028

推荐: