Back to index

moin  1.9.0~rc2
scgi.py
Go to the documentation of this file.
00001 """
00002 .. highlight:: python
00003    :linenothreshold: 5
00004 
00005 .. highlight:: bash
00006    :linenothreshold: 5
00007 
00008 scgi - an SCGI/WSGI gateway.
00009 
00010 :copyright: Copyright (c) 2005, 2006 Allan Saddi <allan@saddi.com>
00011   All rights reserved.
00012 :license:
00013 
00014  Redistribution and use in source and binary forms, with or without
00015  modification, are permitted provided that the following conditions
00016  are met:
00017 
00018  1. Redistributions of source code must retain the above copyright
00019     notice, this list of conditions and the following disclaimer.
00020  2. Redistributions in binary form must reproduce the above copyright
00021     notice, this list of conditions and the following disclaimer in the
00022     documentation and/or other materials provided with the distribution.
00023 
00024  THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS **AS IS** AND
00025  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
00026  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
00027  ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
00028  FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
00029  DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
00030  OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
00031  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
00032  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
00033  OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
00034  SUCH DAMAGE.
00035 
00036 For more information about SCGI and mod_scgi for Apache1/Apache2, see
00037 http://www.mems-exchange.org/software/scgi/.
00038 
00039 For more information about the Web Server Gateway Interface, see
00040 http://www.python.org/peps/pep-0333.html.
00041 
00042 Example usage::
00043 
00044   #!/usr/bin/env python
00045   import sys
00046   from myapplication import app # Assume app is your WSGI application object
00047   from scgi import WSGIServer
00048   ret = WSGIServer(app).run()
00049   sys.exit(ret and 42 or 0)
00050 
00051 See the documentation for WSGIServer for more information.
00052 
00053 About the bit of logic at the end:
00054 Upon receiving SIGHUP, the python script will exit with status code 42. This
00055 can be used by a wrapper script to determine if the python script should be
00056 re-run. When a SIGINT or SIGTERM is received, the script exits with status
00057 code 0, possibly indicating a normal exit.
00058 
00059 Example wrapper script::
00060 
00061   #!/bin/sh
00062   STATUS=42
00063   while test $STATUS -eq 42; do
00064     python "$@" that_script_above.py
00065     STATUS=$?
00066   done
00067 """
00068 
00069 __author__ = 'Allan Saddi <allan@saddi.com>'
00070 __version__ = '$Revision$'
00071 
00072 import logging
00073 import socket
00074 
00075 from flup.server import NoDefault
00076 from flup.server.scgi_base import BaseSCGIServer, Connection
00077 from flup.server.threadedserver import ThreadedServer
00078 
00079 __all__ = ['WSGIServer']
00080 
00081 class WSGIServer(BaseSCGIServer, ThreadedServer):
00082     """
00083     SCGI/WSGI server. For information about SCGI (Simple Common Gateway
00084     Interface), see http://www.mems-exchange.org/software/scgi/.
00085 
00086     This server is similar to SWAP http://www.idyll.org/~t/www-tools/wsgi/,
00087     another SCGI/WSGI server.
00088 
00089     It differs from SWAP in that it isn't based on scgi.scgi_server and
00090     therefore, it allows me to implement concurrency using threads. (Also,
00091     this server was written from scratch and really has no other depedencies.)
00092     Which server to use really boils down to whether you want multithreading
00093     or forking. (But as an aside, I've found scgi.scgi_server's implementation
00094     of preforking to be quite superior. So if your application really doesn't
00095     mind running in multiple processes, go use SWAP. ;)
00096     """
00097     def __init__(self, application, scriptName=NoDefault, environ=None,
00098                  multithreaded=True, multiprocess=False,
00099                  bindAddress=('localhost', 4000), umask=None,
00100                  allowedServers=None,
00101                  loggingLevel=logging.INFO, debug=False, **kw):
00102         """
00103         scriptName is the initial portion of the URL path that "belongs"
00104         to your application. It is used to determine PATH_INFO (which doesn't
00105         seem to be passed in). An empty scriptName means your application
00106         is mounted at the root of your virtual host.
00107 
00108         environ, which must be a dictionary, can contain any additional
00109         environment variables you want to pass to your application.
00110 
00111         bindAddress is the address to bind to, which must be a string or
00112         a tuple of length 2. If a tuple, the first element must be a string,
00113         which is the host name or IPv4 address of a local interface. The
00114         2nd element of the tuple is the port number. If a string, it will
00115         be interpreted as a filename and a UNIX socket will be opened.
00116 
00117         If binding to a UNIX socket, umask may be set to specify what
00118         the umask is to be changed to before the socket is created in the
00119         filesystem. After the socket is created, the previous umask is
00120         restored.
00121 
00122         allowedServers must be None or a list of strings representing the
00123         IPv4 addresses of servers allowed to connect. None means accept
00124         connections from anywhere.
00125 
00126         loggingLevel sets the logging level of the module-level logger.
00127         """
00128         BaseSCGIServer.__init__(self, application,
00129                                 scriptName=scriptName,
00130                                 environ=environ,
00131                                 multithreaded=multithreaded,
00132                                 multiprocess=multiprocess,
00133                                 bindAddress=bindAddress,
00134                                 umask=umask,
00135                                 allowedServers=allowedServers,
00136                                 loggingLevel=loggingLevel,
00137                                 debug=debug)
00138         for key in ('jobClass', 'jobArgs'):
00139             if kw.has_key(key):
00140                 del kw[key]
00141         ThreadedServer.__init__(self, jobClass=Connection, jobArgs=(self,),
00142                                 **kw)
00143 
00144     def run(self):
00145         """
00146         Main loop. Call this after instantiating WSGIServer. SIGHUP, SIGINT,
00147         SIGQUIT, SIGTERM cause it to cleanup and return. (If a SIGHUP
00148         is caught, this method returns True. Returns False otherwise.)
00149         """
00150         self.logger.info('%s starting up', self.__class__.__name__)
00151 
00152         try:
00153             sock = self._setupSocket()
00154         except socket.error, e:
00155             self.logger.error('Failed to bind socket (%s), exiting', e[1])
00156             return False
00157 
00158         ret = ThreadedServer.run(self, sock)
00159 
00160         self._cleanupSocket(sock)
00161         self.shutdown()
00162 
00163         self.logger.info('%s shutting down%s', self.__class__.__name__,
00164                          self._hupReceived and ' (reload requested)' or '')
00165 
00166         return ret
00167 
00168 if __name__ == '__main__':
00169     def test_app(environ, start_response):
00170         """Probably not the most efficient example."""
00171         import cgi
00172         start_response('200 OK', [('Content-Type', 'text/html')])
00173         yield '<html><head><title>Hello World!</title></head>\n' \
00174               '<body>\n' \
00175               '<p>Hello World!</p>\n' \
00176               '<table border="1">'
00177         names = environ.keys()
00178         names.sort()
00179         for name in names:
00180             yield '<tr><td>%s</td><td>%s</td></tr>\n' % (
00181                 name, cgi.escape(`environ[name]`))
00182 
00183         form = cgi.FieldStorage(fp=environ['wsgi.input'], environ=environ,
00184                                 keep_blank_values=1)
00185         if form.list:
00186             yield '<tr><th colspan="2">Form data</th></tr>'
00187 
00188         for field in form.list:
00189             yield '<tr><td>%s</td><td>%s</td></tr>\n' % (
00190                 field.name, field.value)
00191 
00192         yield '</table>\n' \
00193               '</body></html>\n'
00194 
00195     from wsgiref import validate
00196     test_app = validate.validator(test_app)
00197     WSGIServer(test_app,
00198                loggingLevel=logging.DEBUG).run()