fastcgi.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. """
  2. FastCGI (or SCGI, or AJP1.3 ...) server that implements the WSGI protocol.
  3. Uses the flup python package: http://www.saddi.com/software/flup/
  4. This is an adaptation of the flup package to add FastCGI server support
  5. to run Django apps from Web servers that support the FastCGI protocol.
  6. This module can be run standalone or from the django-admin / manage.py
  7. scripts using the "runfcgi" directive.
  8. Run with the extra option "help" for a list of additional options you can
  9. pass to this server.
  10. """
  11. import importlib
  12. import os
  13. import sys
  14. __version__ = "0.1"
  15. __all__ = ["runfastcgi"]
  16. FASTCGI_OPTIONS = {
  17. 'protocol': 'fcgi',
  18. 'host': None,
  19. 'port': None,
  20. 'socket': None,
  21. 'method': 'fork',
  22. 'daemonize': None,
  23. 'workdir': '/',
  24. 'pidfile': None,
  25. 'maxspare': 5,
  26. 'minspare': 2,
  27. 'maxchildren': 50,
  28. 'maxrequests': 0,
  29. 'debug': None,
  30. 'outlog': None,
  31. 'errlog': None,
  32. 'umask': None,
  33. }
  34. FASTCGI_HELP = r"""
  35. Run this project as a fastcgi (or some other protocol supported
  36. by flup) application. To do this, the flup package from
  37. http://www.saddi.com/software/flup/ is required.
  38. runfcgi [options] [fcgi settings]
  39. Optional Fcgi settings: (setting=value)
  40. protocol=PROTOCOL fcgi, scgi, ajp, ... (default %(protocol)s)
  41. host=HOSTNAME hostname to listen on.
  42. port=PORTNUM port to listen on.
  43. socket=FILE UNIX socket to listen on.
  44. method=IMPL prefork or threaded (default %(method)s).
  45. maxrequests=NUMBER number of requests a child handles before it is
  46. killed and a new child is forked (0 = no limit).
  47. maxspare=NUMBER max number of spare processes / threads (default %(maxspare)s).
  48. minspare=NUMBER min number of spare processes / threads (default %(minspare)s).
  49. maxchildren=NUMBER hard limit number of processes / threads (default %(maxchildren)s).
  50. daemonize=BOOL whether to detach from terminal.
  51. pidfile=FILE write the spawned process-id to this file.
  52. workdir=DIRECTORY change to this directory when daemonizing (default %(workdir)s).
  53. debug=BOOL set to true to enable flup tracebacks.
  54. outlog=FILE write stdout to this file.
  55. errlog=FILE write stderr to this file.
  56. umask=UMASK umask to use when daemonizing, in octal notation (default 022).
  57. Examples:
  58. Run a "standard" fastcgi process on a file-descriptor
  59. (for Web servers which spawn your processes for you)
  60. $ manage.py runfcgi method=threaded
  61. Run a scgi server on a TCP host/port
  62. $ manage.py runfcgi protocol=scgi method=prefork host=127.0.0.1 port=8025
  63. Run a fastcgi server on a UNIX domain socket (posix platforms only)
  64. $ manage.py runfcgi method=prefork socket=/tmp/fcgi.sock
  65. Run a fastCGI as a daemon and write the spawned PID in a file
  66. $ manage.py runfcgi socket=/tmp/fcgi.sock method=prefork \
  67. daemonize=true pidfile=/var/run/django-fcgi.pid
  68. """ % FASTCGI_OPTIONS
  69. def fastcgi_help(message=None):
  70. print(FASTCGI_HELP)
  71. if message:
  72. print(message)
  73. return False
  74. def runfastcgi(argset=[], **kwargs):
  75. options = FASTCGI_OPTIONS.copy()
  76. options.update(kwargs)
  77. for x in argset:
  78. if "=" in x:
  79. k, v = x.split('=', 1)
  80. else:
  81. k, v = x, True
  82. options[k.lower()] = v
  83. if "help" in options:
  84. return fastcgi_help()
  85. try:
  86. import flup # NOQA
  87. except ImportError as e:
  88. sys.stderr.write("ERROR: %s\n" % e)
  89. sys.stderr.write(" Unable to load the flup package. In order to run django\n")
  90. sys.stderr.write(" as a FastCGI application, you will need to get flup from\n")
  91. sys.stderr.write(" http://www.saddi.com/software/flup/ If you've already\n")
  92. sys.stderr.write(" installed flup, then make sure you have it in your PYTHONPATH.\n")
  93. return False
  94. flup_module = 'server.' + options['protocol']
  95. if options['method'] in ('prefork', 'fork'):
  96. wsgi_opts = {
  97. 'maxSpare': int(options["maxspare"]),
  98. 'minSpare': int(options["minspare"]),
  99. 'maxChildren': int(options["maxchildren"]),
  100. 'maxRequests': int(options["maxrequests"]),
  101. }
  102. flup_module += '_fork'
  103. elif options['method'] in ('thread', 'threaded'):
  104. wsgi_opts = {
  105. 'maxSpare': int(options["maxspare"]),
  106. 'minSpare': int(options["minspare"]),
  107. 'maxThreads': int(options["maxchildren"]),
  108. }
  109. else:
  110. return fastcgi_help("ERROR: Implementation must be one of prefork or "
  111. "thread.")
  112. wsgi_opts['debug'] = options['debug'] is not None
  113. try:
  114. module = importlib.import_module('.%s' % flup_module, 'flup')
  115. WSGIServer = module.WSGIServer
  116. except Exception:
  117. print("Can't import flup." + flup_module)
  118. return False
  119. # Prep up and go
  120. from django.core.servers.basehttp import get_internal_wsgi_application
  121. if options["host"] and options["port"] and not options["socket"]:
  122. wsgi_opts['bindAddress'] = (options["host"], int(options["port"]))
  123. elif options["socket"] and not options["host"] and not options["port"]:
  124. wsgi_opts['bindAddress'] = options["socket"]
  125. elif not options["socket"] and not options["host"] and not options["port"]:
  126. wsgi_opts['bindAddress'] = None
  127. else:
  128. return fastcgi_help("Invalid combination of host, port, socket.")
  129. if options["daemonize"] is None:
  130. # Default to daemonizing if we're running on a socket/named pipe.
  131. daemonize = (wsgi_opts['bindAddress'] is not None)
  132. else:
  133. if options["daemonize"].lower() in ('true', 'yes', 't'):
  134. daemonize = True
  135. elif options["daemonize"].lower() in ('false', 'no', 'f'):
  136. daemonize = False
  137. else:
  138. return fastcgi_help("ERROR: Invalid option for daemonize "
  139. "parameter.")
  140. daemon_kwargs = {}
  141. if options['outlog']:
  142. daemon_kwargs['out_log'] = options['outlog']
  143. if options['errlog']:
  144. daemon_kwargs['err_log'] = options['errlog']
  145. if options['umask']:
  146. daemon_kwargs['umask'] = int(options['umask'], 8)
  147. if daemonize:
  148. from django.utils.daemonize import become_daemon
  149. become_daemon(our_home_dir=options["workdir"], **daemon_kwargs)
  150. if options["pidfile"]:
  151. with open(options["pidfile"], "w") as fp:
  152. fp.write("%d\n" % os.getpid())
  153. WSGIServer(get_internal_wsgi_application(), **wsgi_opts).run()
  154. if __name__ == '__main__':
  155. runfastcgi(sys.argv[1:])