fcgi.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. # Copyright (c) 2005, 2006 Allan Saddi <allan@saddi.com>
  2. # All rights reserved.
  3. #
  4. # Redistribution and use in source and binary forms, with or without
  5. # modification, are permitted provided that the following conditions
  6. # are met:
  7. # 1. Redistributions of source code must retain the above copyright
  8. # notice, this list of conditions and the following disclaimer.
  9. # 2. Redistributions in binary form must reproduce the above copyright
  10. # notice, this list of conditions and the following disclaimer in the
  11. # documentation and/or other materials provided with the distribution.
  12. #
  13. # THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
  14. # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  15. # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  16. # ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  17. # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  18. # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  19. # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  20. # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  21. # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  22. # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  23. # SUCH DAMAGE.
  24. #
  25. # $Id$
  26. """
  27. fcgi - a FastCGI/WSGI gateway.
  28. For more information about FastCGI, see <http://www.fastcgi.com/>.
  29. For more information about the Web Server Gateway Interface, see
  30. <http://www.python.org/peps/pep-0333.html>.
  31. Example usage:
  32. #!/usr/bin/env python
  33. from myapplication import app # Assume app is your WSGI application object
  34. from fcgi import WSGIServer
  35. WSGIServer(app).run()
  36. See the documentation for WSGIServer for more information.
  37. On most platforms, fcgi will fallback to regular CGI behavior if run in a
  38. non-FastCGI context. If you want to force CGI behavior, set the environment
  39. variable FCGI_FORCE_CGI to "Y" or "y".
  40. """
  41. __author__ = 'Allan Saddi <allan@saddi.com>'
  42. __version__ = '$Revision$'
  43. import os
  44. from flup.server.fcgi_base import BaseFCGIServer, FCGI_RESPONDER
  45. from flup.server.threadedserver import ThreadedServer
  46. __all__ = ['WSGIServer']
  47. class WSGIServer(BaseFCGIServer, ThreadedServer):
  48. """
  49. FastCGI server that supports the Web Server Gateway Interface. See
  50. <http://www.python.org/peps/pep-0333.html>.
  51. """
  52. def __init__(self, application, environ=None,
  53. multithreaded=True, multiprocess=False,
  54. bindAddress=None, umask=None, multiplexed=False,
  55. debug=True, roles=(FCGI_RESPONDER,), forceCGI=False, **kw):
  56. """
  57. environ, if present, must be a dictionary-like object. Its
  58. contents will be copied into application's environ. Useful
  59. for passing application-specific variables.
  60. bindAddress, if present, must either be a string or a 2-tuple. If
  61. present, run() will open its own listening socket. You would use
  62. this if you wanted to run your application as an 'external' FastCGI
  63. app. (i.e. the webserver would no longer be responsible for starting
  64. your app) If a string, it will be interpreted as a filename and a UNIX
  65. socket will be opened. If a tuple, the first element, a string,
  66. is the interface name/IP to bind to, and the second element (an int)
  67. is the port number.
  68. """
  69. BaseFCGIServer.__init__(self, application,
  70. environ=environ,
  71. multithreaded=multithreaded,
  72. multiprocess=multiprocess,
  73. bindAddress=bindAddress,
  74. umask=umask,
  75. multiplexed=multiplexed,
  76. debug=debug,
  77. roles=roles,
  78. forceCGI=forceCGI)
  79. for key in ('jobClass', 'jobArgs'):
  80. if kw.has_key(key):
  81. del kw[key]
  82. ThreadedServer.__init__(self, jobClass=self._connectionClass,
  83. jobArgs=(self,), **kw)
  84. def _isClientAllowed(self, addr):
  85. return self._web_server_addrs is None or \
  86. (len(addr) == 2 and addr[0] in self._web_server_addrs)
  87. def run(self):
  88. """
  89. The main loop. Exits on SIGHUP, SIGINT, SIGTERM. Returns True if
  90. SIGHUP was received, False otherwise.
  91. """
  92. self._web_server_addrs = os.environ.get('FCGI_WEB_SERVER_ADDRS')
  93. if self._web_server_addrs is not None:
  94. self._web_server_addrs = map(lambda x: x.strip(),
  95. self._web_server_addrs.split(','))
  96. sock = self._setupSocket()
  97. ret = ThreadedServer.run(self, sock)
  98. self._cleanupSocket(sock)
  99. return ret
  100. if __name__ == '__main__':
  101. def test_app(environ, start_response):
  102. """Probably not the most efficient example."""
  103. import cgi
  104. start_response('200 OK', [('Content-Type', 'text/html')])
  105. yield '<html><head><title>Hello World!</title></head>\n' \
  106. '<body>\n' \
  107. '<p>Hello World!</p>\n' \
  108. '<table border="1">'
  109. names = environ.keys()
  110. names.sort()
  111. for name in names:
  112. yield '<tr><td>%s</td><td>%s</td></tr>\n' % (
  113. name, cgi.escape(`environ[name]`))
  114. form = cgi.FieldStorage(fp=environ['wsgi.input'], environ=environ,
  115. keep_blank_values=1)
  116. if form.list:
  117. yield '<tr><th colspan="2">Form data</th></tr>'
  118. for field in form.list:
  119. yield '<tr><td>%s</td><td>%s</td></tr>\n' % (
  120. field.name, field.value)
  121. yield '</table>\n' \
  122. '</body></html>\n'
  123. from wsgiref import validate
  124. test_app = validate.validator(test_app)
  125. WSGIServer(test_app).run()