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"""
28fcgi - a FastCGI/WSGI gateway.
29
30For more information about FastCGI, see <http://www.fastcgi.com/>.
31
32For more information about the Web Server Gateway Interface, see
33<http://www.python.org/peps/pep-0333.html>.
34
35Example usage:
36
37  #!/usr/bin/env python
38  from myapplication import app # Assume app is your WSGI application object
39  from fcgi import WSGIServer
40  WSGIServer(app).run()
41
42See the documentation for WSGIServer for more information.
43
44On most platforms, fcgi will fallback to regular CGI behavior if run in a
45non-FastCGI context. If you want to force CGI behavior, set the environment
46variable FCGI_FORCE_CGI to "Y" or "y".
47"""
48
49__author__ = 'Allan Saddi <allan@saddi.com>'
50__version__ = '$Revision$'
51
52import os
53
54from flup.server.fcgi_base import BaseFCGIServer, FCGI_RESPONDER
55from flup.server.threadedserver import ThreadedServer
56
57__all__ = ['WSGIServer']
58
59class WSGIServer(BaseFCGIServer, ThreadedServer):
60    """
61    FastCGI server that supports the Web Server Gateway Interface. See
62    <http://www.python.org/peps/pep-0333.html>.
63    """
64    def __init__(self, application, environ=None,
65                 multithreaded=True, multiprocess=False,
66                 bindAddress=None, umask=None, multiplexed=False,
67                 debug=False, roles=(FCGI_RESPONDER,), forceCGI=False, **kw):
68        """
69        environ, if present, must be a dictionary-like object. Its
70        contents will be copied into application's environ. Useful
71        for passing application-specific variables.
72
73        bindAddress, if present, must either be a string or a 2-tuple. If
74        present, run() will open its own listening socket. You would use
75        this if you wanted to run your application as an 'external' FastCGI
76        app. (i.e. the webserver would no longer be responsible for starting
77        your app) If a string, it will be interpreted as a filename and a UNIX
78        socket will be opened. If a tuple, the first element, a string,
79        is the interface name/IP to bind to, and the second element (an int)
80        is the port number.
81        """
82        BaseFCGIServer.__init__(self, application,
83                                environ=environ,
84                                multithreaded=multithreaded,
85                                multiprocess=multiprocess,
86                                bindAddress=bindAddress,
87                                umask=umask,
88                                multiplexed=multiplexed,
89                                debug=debug,
90                                roles=roles,
91                                forceCGI=forceCGI)
92        for key in ('jobClass', 'jobArgs'):
93            if kw.has_key(key):
94                del kw[key]
95        ThreadedServer.__init__(self, jobClass=self._connectionClass,
96                                jobArgs=(self, None), **kw)
97
98    def _isClientAllowed(self, addr):
99        return self._web_server_addrs is None or \
100               (len(addr) == 2 and addr[0] in self._web_server_addrs)
101
102    def run(self):
103        """
104        The main loop. Exits on SIGHUP, SIGINT, SIGTERM. Returns True if
105        SIGHUP was received, False otherwise.
106        """
107        self._web_server_addrs = os.environ.get('FCGI_WEB_SERVER_ADDRS')
108        if self._web_server_addrs is not None:
109            self._web_server_addrs = map(lambda x: x.strip(),
110                                         self._web_server_addrs.split(','))
111
112        sock = self._setupSocket()
113
114        ret = ThreadedServer.run(self, sock)
115
116        self._cleanupSocket(sock)
117        self.shutdown()
118
119        return ret
120
121if __name__ == '__main__':
122    def test_app(environ, start_response):
123        """Probably not the most efficient example."""
124        import cgi
125        start_response('200 OK', [('Content-Type', 'text/html')])
126        yield '<html><head><title>Hello World!</title></head>\n' \
127              '<body>\n' \
128              '<p>Hello World!</p>\n' \
129              '<table border="1">'
130        names = environ.keys()
131        names.sort()
132        for name in names:
133            yield '<tr><td>%s</td><td>%s</td></tr>\n' % (
134                name, cgi.escape(`environ[name]`))
135
136        form = cgi.FieldStorage(fp=environ['wsgi.input'], environ=environ,
137                                keep_blank_values=1)
138        if form.list:
139            yield '<tr><th colspan="2">Form data</th></tr>'
140
141        for field in form.list:
142            yield '<tr><td>%s</td><td>%s</td></tr>\n' % (
143                field.name, field.value)
144
145        yield '</table>\n' \
146              '</body></html>\n'
147
148    from wsgiref import validate
149    test_app = validate.validator(test_app)
150    WSGIServer(test_app).run()
151