8
ajp - an AJP 1.3/WSGI gateway.
10
:copyright: Copyright (c) 2005, 2006 Allan Saddi <allan@saddi.com>
14
Redistribution and use in source and binary forms, with or without
15
modification, are permitted provided that the following conditions
18
1. Redistributions of source code must retain the above copyright
19
notice, this list of conditions and the following disclaimer.
20
2. Redistributions in binary form must reproduce the above copyright
21
notice, this list of conditions and the following disclaimer in the
22
documentation and/or other materials provided with the distribution.
24
THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS **AS IS** AND
25
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
28
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33
OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36
For more information about AJP and AJP connectors for your web server, see
37
http://jakarta.apache.org/tomcat/connectors-doc/.
39
For more information about the Web Server Gateway Interface, see
40
http://www.python.org/peps/pep-0333.html.
46
from myapplication import app # Assume app is your WSGI application object
47
from ajp import WSGIServer
48
ret = WSGIServer(app).run()
49
sys.exit(ret and 42 or 0)
51
See the documentation for WSGIServer for more information.
53
About the bit of logic at the end:
54
Upon receiving SIGHUP, the python script will exit with status code 42. This
55
can be used by a wrapper script to determine if the python script should be
56
re-run. When a SIGINT or SIGTERM is received, the script exits with status
57
code 0, possibly indicating a normal exit.
59
Example wrapper script::
63
while test $STATUS -eq 42; do
64
python "$@" that_script_above.py
68
Example workers.properties (for mod_jk)::
72
worker.foo.host=localhost
75
Example httpd.conf (for mod_jk)::
77
JkWorkersFile /path/to/workers.properties
80
Note that if you mount your ajp application anywhere but the root ("/"), you
81
SHOULD specifiy scriptName to the WSGIServer constructor. This will ensure
82
that SCRIPT_NAME/PATH_INFO are correctly deduced.
85
__author__ = 'Allan Saddi <allan@saddi.com>'
86
__version__ = '$Revision$'
91
from flup.server.ajp_base import BaseAJPServer, Connection
92
from flup.server.preforkserver import PreforkServer
94
__all__ = ['WSGIServer']
96
class WSGIServer(BaseAJPServer, PreforkServer):
98
AJP1.3/WSGI server. Runs your WSGI application as a persistant program
99
that understands AJP1.3. Opens up a TCP socket, binds it, and then
100
waits for forwarded requests from your webserver.
102
Why AJP? Two good reasons are that AJP provides load-balancing and
103
fail-over support. Personally, I just wanted something new to
106
Of course you will need an AJP1.3 connector for your webserver (e.g.
107
mod_jk) - see http://jakarta.apache.org/tomcat/connectors-doc/.
109
def __init__(self, application, scriptName='', environ=None,
110
bindAddress=('localhost', 8009), allowedServers=None,
111
loggingLevel=logging.INFO, debug=False, timeout=None, **kw):
113
scriptName is the initial portion of the URL path that "belongs"
114
to your application. It is used to determine PATH_INFO (which doesn't
115
seem to be passed in). An empty scriptName means your application
116
is mounted at the root of your virtual host.
118
environ, which must be a dictionary, can contain any additional
119
environment variables you want to pass to your application.
121
bindAddress is the address to bind to, which must be a tuple of
122
length 2. The first element is a string, which is the host name
123
or IPv4 address of a local interface. The 2nd element is the port
126
allowedServers must be None or a list of strings representing the
127
IPv4 addresses of servers allowed to connect. None means accept
128
connections from anywhere.
130
loggingLevel sets the logging level of the module-level logger.
132
BaseAJPServer.__init__(self, application,
133
scriptName=scriptName,
137
bindAddress=bindAddress,
138
allowedServers=allowedServers,
139
loggingLevel=loggingLevel,
141
for key in ('multithreaded', 'multiprocess', 'jobClass', 'jobArgs'):
144
PreforkServer.__init__(self, jobClass=Connection,
145
jobArgs=(self, timeout), **kw)
149
Main loop. Call this after instantiating WSGIServer. SIGHUP, SIGINT,
150
SIGQUIT, SIGTERM cause it to cleanup and return. (If a SIGHUP
151
is caught, this method returns True. Returns False otherwise.)
153
self.logger.info('%s starting up', self.__class__.__name__)
156
sock = self._setupSocket()
157
except socket.error, e:
158
self.logger.error('Failed to bind socket (%s), exiting', e[1])
161
ret = PreforkServer.run(self, sock)
163
self._cleanupSocket(sock)
165
self.logger.info('%s shutting down%s', self.__class__.__name__,
166
self._hupReceived and ' (reload requested)' or '')
170
if __name__ == '__main__':
171
def test_app(environ, start_response):
172
"""Probably not the most efficient example."""
174
start_response('200 OK', [('Content-Type', 'text/html')])
175
yield '<html><head><title>Hello World!</title></head>\n' \
177
'<p>Hello World!</p>\n' \
179
names = environ.keys()
182
yield '<tr><td>%s</td><td>%s</td></tr>\n' % (
183
name, cgi.escape(`environ[name]`))
185
form = cgi.FieldStorage(fp=environ['wsgi.input'], environ=environ,
188
yield '<tr><th colspan="2">Form data</th></tr>'
190
for field in form.list:
191
yield '<tr><td>%s</td><td>%s</td></tr>\n' % (
192
field.name, field.value)
197
from wsgiref import validate
198
test_app = validate.validator(test_app)
199
# Explicitly set bindAddress to *:8009 for testing.
201
bindAddress=('', 8009), allowedServers=None,
202
loggingLevel=logging.DEBUG).run()