PageRenderTime 45ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/junk/python/chat/flup/server/scgi_fork.py

http://pytof.googlecode.com/
Python | 192 lines | 135 code | 1 blank | 56 comment | 0 complexity | 19201d3c37abf05276fd547a5814f29a MD5 | raw file
Possible License(s): BSD-3-Clause, Apache-2.0, GPL-3.0, GPL-2.0, IPL-1.0
  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: scgi_fork.py 2306 2007-01-02 22:15:53Z asaddi $
  26. """
  27. scgi - an SCGI/WSGI gateway.
  28. For more information about SCGI and mod_scgi for Apache1/Apache2, see
  29. <http://www.mems-exchange.org/software/scgi/>.
  30. For more information about the Web Server Gateway Interface, see
  31. <http://www.python.org/peps/pep-0333.html>.
  32. Example usage:
  33. #!/usr/bin/env python
  34. import sys
  35. from myapplication import app # Assume app is your WSGI application object
  36. from scgi import WSGIServer
  37. ret = WSGIServer(app).run()
  38. sys.exit(ret and 42 or 0)
  39. See the documentation for WSGIServer for more information.
  40. About the bit of logic at the end:
  41. Upon receiving SIGHUP, the python script will exit with status code 42. This
  42. can be used by a wrapper script to determine if the python script should be
  43. re-run. When a SIGINT or SIGTERM is received, the script exits with status
  44. code 0, possibly indicating a normal exit.
  45. Example wrapper script:
  46. #!/bin/sh
  47. STATUS=42
  48. while test $STATUS -eq 42; do
  49. python "$@" that_script_above.py
  50. STATUS=$?
  51. done
  52. """
  53. __author__ = 'Allan Saddi <allan@saddi.com>'
  54. __version__ = '$Revision: 2306 $'
  55. import logging
  56. import socket
  57. from flup.server.scgi_base import BaseSCGIServer, Connection, NoDefault
  58. from flup.server.preforkserver import PreforkServer
  59. __all__ = ['WSGIServer']
  60. class WSGIServer(BaseSCGIServer, PreforkServer):
  61. """
  62. SCGI/WSGI server. For information about SCGI (Simple Common Gateway
  63. Interface), see <http://www.mems-exchange.org/software/scgi/>.
  64. This server is similar to SWAP <http://www.idyll.org/~t/www-tools/wsgi/>,
  65. another SCGI/WSGI server.
  66. It differs from SWAP in that it isn't based on scgi.scgi_server and
  67. therefore, it allows me to implement concurrency using threads. (Also,
  68. this server was written from scratch and really has no other depedencies.)
  69. Which server to use really boils down to whether you want multithreading
  70. or forking. (But as an aside, I've found scgi.scgi_server's implementation
  71. of preforking to be quite superior. So if your application really doesn't
  72. mind running in multiple processes, go use SWAP. ;)
  73. """
  74. def __init__(self, application, scriptName=NoDefault, environ=None,
  75. bindAddress=('localhost', 4000), umask=None,
  76. allowedServers=None,
  77. loggingLevel=logging.INFO, debug=True, **kw):
  78. """
  79. scriptName is the initial portion of the URL path that "belongs"
  80. to your application. It is used to determine PATH_INFO (which doesn't
  81. seem to be passed in). An empty scriptName means your application
  82. is mounted at the root of your virtual host.
  83. environ, which must be a dictionary, can contain any additional
  84. environment variables you want to pass to your application.
  85. bindAddress is the address to bind to, which must be a string or
  86. a tuple of length 2. If a tuple, the first element must be a string,
  87. which is the host name or IPv4 address of a local interface. The
  88. 2nd element of the tuple is the port number. If a string, it will
  89. be interpreted as a filename and a UNIX socket will be opened.
  90. If binding to a UNIX socket, umask may be set to specify what
  91. the umask is to be changed to before the socket is created in the
  92. filesystem. After the socket is created, the previous umask is
  93. restored.
  94. allowedServers must be None or a list of strings representing the
  95. IPv4 addresses of servers allowed to connect. None means accept
  96. connections from anywhere.
  97. loggingLevel sets the logging level of the module-level logger.
  98. """
  99. BaseSCGIServer.__init__(self, application,
  100. scriptName=scriptName,
  101. environ=environ,
  102. multithreaded=False,
  103. multiprocess=True,
  104. bindAddress=bindAddress,
  105. umask=umask,
  106. allowedServers=allowedServers,
  107. loggingLevel=loggingLevel,
  108. debug=debug)
  109. for key in ('multithreaded', 'multiprocess', 'jobClass', 'jobArgs'):
  110. if kw.has_key(key):
  111. del kw[key]
  112. PreforkServer.__init__(self, jobClass=Connection, jobArgs=(self,), **kw)
  113. def run(self):
  114. """
  115. Main loop. Call this after instantiating WSGIServer. SIGHUP, SIGINT,
  116. SIGQUIT, SIGTERM cause it to cleanup and return. (If a SIGHUP
  117. is caught, this method returns True. Returns False otherwise.)
  118. """
  119. self.logger.info('%s starting up', self.__class__.__name__)
  120. try:
  121. sock = self._setupSocket()
  122. except socket.error, e:
  123. self.logger.error('Failed to bind socket (%s), exiting', e[1])
  124. return False
  125. ret = PreforkServer.run(self, sock)
  126. self._cleanupSocket(sock)
  127. self.logger.info('%s shutting down%s', self.__class__.__name__,
  128. self._hupReceived and ' (reload requested)' or '')
  129. return ret
  130. def factory(global_conf, host=None, port=None, **local):
  131. import paste_factory
  132. return paste_factory.helper(WSGIServer, global_conf, host, port, **local)
  133. if __name__ == '__main__':
  134. def test_app(environ, start_response):
  135. """Probably not the most efficient example."""
  136. import cgi
  137. start_response('200 OK', [('Content-Type', 'text/html')])
  138. yield '<html><head><title>Hello World!</title></head>\n' \
  139. '<body>\n' \
  140. '<p>Hello World!</p>\n' \
  141. '<table border="1">'
  142. names = environ.keys()
  143. names.sort()
  144. for name in names:
  145. yield '<tr><td>%s</td><td>%s</td></tr>\n' % (
  146. name, cgi.escape(`environ[name]`))
  147. form = cgi.FieldStorage(fp=environ['wsgi.input'], environ=environ,
  148. keep_blank_values=1)
  149. if form.list:
  150. yield '<tr><th colspan="2">Form data</th></tr>'
  151. for field in form.list:
  152. yield '<tr><td>%s</td><td>%s</td></tr>\n' % (
  153. field.name, field.value)
  154. yield '</table>\n' \
  155. '</body></html>\n'
  156. from wsgiref import validate
  157. test_app = validate.validator(test_app)
  158. WSGIServer(test_app,
  159. loggingLevel=logging.DEBUG).run()