/
wsgihttpserver.py
170 lines (142 loc) · 6.56 KB
/
wsgihttpserver.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
##############################################################################
#
# Copyright (c) 2001, 2002 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""WSGI-compliant HTTP Server that uses the Zope Publisher for executing a task.
"""
import asyncore
import re
import sys
from zope.server.http.httpserver import HTTPServer
from zope.server.taskthreads import ThreadedTaskDispatcher
import zope.security.management
def fakeWrite(body):
raise NotImplementedError(
"Zope 3's HTTP Server does not support the WSGI write() function.")
class WSGIHTTPServer(HTTPServer):
"""Zope Publisher-specific WSGI-compliant HTTP Server"""
application = None
def __init__(self, application, sub_protocol=None, *args, **kw):
if sys.platform[:3] == "win" and args[0] == 'localhost':
args = ('',) + args[1:]
self.application = application
if sub_protocol:
self.SERVER_IDENT += ' (%s)' %str(sub_protocol)
HTTPServer.__init__(self, *args, **kw)
def _constructWSGIEnvironment(self, task):
env = task.getCGIEnvironment()
# deduce the URL scheme (http or https)
if (env.get('HTTPS', '').lower() == "on" or
env.get('SERVER_PORT_SECURE') == "1"):
protocol = 'https'
else:
protocol = 'http'
# the following environment variables are required by the WSGI spec
env['wsgi.version'] = (1,0)
env['wsgi.url_scheme'] = protocol
env['wsgi.errors'] = sys.stderr # apps should use the logging module
env['wsgi.multithread'] = True
env['wsgi.multiprocess'] = True
env['wsgi.run_once'] = False
env['wsgi.input'] = task.request_data.getBodyStream()
# Add some proprietary proxy information.
# Note: Derived request parsers might not have these new attributes,
# so fail gracefully.
try:
env['zserver.proxy.scheme'] = task.request_data.proxy_scheme
env['zserver.proxy.host'] = task.request_data.proxy_netloc
except AttributeError:
pass
return env
def executeRequest(self, task):
"""Overrides HTTPServer.executeRequest()."""
env = self._constructWSGIEnvironment(task)
def start_response(status, headers, exc_info=None):
if task.wroteResponseHeader() and not exc_info:
raise AssertionError("start_response called a second time "
"without providing exc_info.")
if exc_info:
try:
if task.wroteResponseHeader():
# higher levels will catch and handle raised exception:
# 1. "service" method in httptask.py
# 2. "service" method in severchannelbase.py
# 3. "handlerThread" method in taskthreads.py
raise exc_info[0], exc_info[1], exc_info[2]
else:
# As per WSGI spec existing headers must be cleared
task.accumulated_headers = None
finally:
exc_info = None
# Prepare the headers for output
status, reason = re.match('([0-9]*) (.*)', status).groups()
task.setResponseStatus(status, reason)
task.appendResponseHeaders(['%s: %s' % i for i in headers])
# Return the write method used to write the response data.
return fakeWrite
# Call the application to handle the request and write a response
result = self.application(env, start_response)
# By iterating manually at this point, we execute task.write()
# multiple times, allowing partial data to be sent.
for value in result:
task.write(value)
class PMDBWSGIHTTPServer(WSGIHTTPServer):
"""Enter the post-mortem debugger when there's an error"""
def executeRequest(self, task):
"""Overrides HTTPServer.executeRequest()."""
env = self._constructWSGIEnvironment(task)
env['wsgi.handleErrors'] = False
def start_response(status, headers, exc_info=None):
if task.wroteResponseHeader() and not exc_info:
raise AssertionError("start_response called a second time "
"without providing exc_info.")
if exc_info:
try:
if task.wroteResponseHeader():
raise exc_info[0], exc_info[1], exc_info[2]
else:
# As per WSGI spec existing headers must be cleared
task.accumulated_headers = None
finally:
exc_info = None
# Prepare the headers for output
status, reason = re.match('([0-9]*) (.*)', status).groups()
task.setResponseStatus(status, reason)
task.appendResponseHeaders(['%s: %s' % i for i in headers])
# Return the write method used to write the response data.
return fakeWrite
# Call the application to handle the request and write a response
try:
result = self.application(env, start_response)
# By iterating manually at this point, we execute task.write()
# multiple times, allowing partial data to be sent.
for value in result:
task.write(value)
except:
import sys, pdb
print "%s:" % sys.exc_info()[0]
print sys.exc_info()[1]
zope.security.management.restoreInteraction()
try:
pdb.post_mortem(sys.exc_info()[2])
raise
finally:
zope.security.management.endInteraction()
def run_paste(wsgi_app, global_conf, name='zope.server.http',
host='127.0.0.1', port=8080, threads=4):
port = int(port)
threads = int(threads)
task_dispatcher = ThreadedTaskDispatcher()
task_dispatcher.setThreadCount(threads)
server = WSGIHTTPServer(wsgi_app, name, host, port,
task_dispatcher=task_dispatcher)
asyncore.loop()