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.threadedserver import ThreadedServer
94
__all__ = ['WSGIServer']
96
class WSGIServer(BaseAJPServer, ThreadedServer):
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
multithreaded=True, multiprocess=False,
111
bindAddress=('localhost', 8009), allowedServers=None,
112
loggingLevel=logging.INFO, debug=False, **kw):
114
scriptName is the initial portion of the URL path that "belongs"
115
to your application. It is used to determine PATH_INFO (which doesn't
116
seem to be passed in). An empty scriptName means your application
117
is mounted at the root of your virtual host.
119
environ, which must be a dictionary, can contain any additional
120
environment variables you want to pass to your application.
122
bindAddress is the address to bind to, which must be a tuple of
123
length 2. The first element is a string, which is the host name
124
or IPv4 address of a local interface. The 2nd element is the port
127
allowedServers must be None or a list of strings representing the
128
IPv4 addresses of servers allowed to connect. None means accept
129
connections from anywhere.
131
loggingLevel sets the logging level of the module-level logger.
133
BaseAJPServer.__init__(self, application,
134
scriptName=scriptName,
136
multithreaded=multithreaded,
137
multiprocess=multiprocess,
138
bindAddress=bindAddress,
139
allowedServers=allowedServers,
140
loggingLevel=loggingLevel,
142
for key in ('jobClass', 'jobArgs'):
145
ThreadedServer.__init__(self, jobClass=Connection,
146
jobArgs=(self, None), **kw)
150
Main loop. Call this after instantiating WSGIServer. SIGHUP, SIGINT,
151
SIGQUIT, SIGTERM cause it to cleanup and return. (If a SIGHUP
152
is caught, this method returns True. Returns False otherwise.)
154
self.logger.info('%s starting up', self.__class__.__name__)
157
sock = self._setupSocket()
158
except socket.error, e:
159
self.logger.error('Failed to bind socket (%s), exiting', e[1])
162
ret = ThreadedServer.run(self, sock)
164
self._cleanupSocket(sock)
165
# AJP connections are more or less persistent. .shutdown() will
166
# not return until the web server lets go. So don't bother calling
170
self.logger.info('%s shutting down%s', self.__class__.__name__,
171
self._hupReceived and ' (reload requested)' or '')
175
if __name__ == '__main__':
176
def test_app(environ, start_response):
177
"""Probably not the most efficient example."""
179
start_response('200 OK', [('Content-Type', 'text/html')])
180
yield '<html><head><title>Hello World!</title></head>\n' \
182
'<p>Hello World!</p>\n' \
184
names = environ.keys()
187
yield '<tr><td>%s</td><td>%s</td></tr>\n' % (
188
name, cgi.escape(`environ[name]`))
190
form = cgi.FieldStorage(fp=environ['wsgi.input'], environ=environ,
193
yield '<tr><th colspan="2">Form data</th></tr>'
195
for field in form.list:
196
yield '<tr><td>%s</td><td>%s</td></tr>\n' % (
197
field.name, field.value)
202
from wsgiref import validate
203
test_app = validate.validator(test_app)
204
# Explicitly set bindAddress to *:8009 for testing.
206
bindAddress=('', 8009), allowedServers=None,
207
loggingLevel=logging.DEBUG).run()