1 | n/a | """Base classes for server/gateway implementations""" |
---|
2 | n/a | |
---|
3 | n/a | from .util import FileWrapper, guess_scheme, is_hop_by_hop |
---|
4 | n/a | from .headers import Headers |
---|
5 | n/a | |
---|
6 | n/a | import sys, os, time |
---|
7 | n/a | |
---|
8 | n/a | __all__ = [ |
---|
9 | n/a | 'BaseHandler', 'SimpleHandler', 'BaseCGIHandler', 'CGIHandler', |
---|
10 | n/a | 'IISCGIHandler', 'read_environ' |
---|
11 | n/a | ] |
---|
12 | n/a | |
---|
13 | n/a | # Weekday and month names for HTTP date/time formatting; always English! |
---|
14 | n/a | _weekdayname = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"] |
---|
15 | n/a | _monthname = [None, # Dummy so we can use 1-based month numbers |
---|
16 | n/a | "Jan", "Feb", "Mar", "Apr", "May", "Jun", |
---|
17 | n/a | "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] |
---|
18 | n/a | |
---|
19 | n/a | def format_date_time(timestamp): |
---|
20 | n/a | year, month, day, hh, mm, ss, wd, y, z = time.gmtime(timestamp) |
---|
21 | n/a | return "%s, %02d %3s %4d %02d:%02d:%02d GMT" % ( |
---|
22 | n/a | _weekdayname[wd], day, _monthname[month], year, hh, mm, ss |
---|
23 | n/a | ) |
---|
24 | n/a | |
---|
25 | n/a | _is_request = { |
---|
26 | n/a | 'SCRIPT_NAME', 'PATH_INFO', 'QUERY_STRING', 'REQUEST_METHOD', 'AUTH_TYPE', |
---|
27 | n/a | 'CONTENT_TYPE', 'CONTENT_LENGTH', 'HTTPS', 'REMOTE_USER', 'REMOTE_IDENT', |
---|
28 | n/a | }.__contains__ |
---|
29 | n/a | |
---|
30 | n/a | def _needs_transcode(k): |
---|
31 | n/a | return _is_request(k) or k.startswith('HTTP_') or k.startswith('SSL_') \ |
---|
32 | n/a | or (k.startswith('REDIRECT_') and _needs_transcode(k[9:])) |
---|
33 | n/a | |
---|
34 | n/a | def read_environ(): |
---|
35 | n/a | """Read environment, fixing HTTP variables""" |
---|
36 | n/a | enc = sys.getfilesystemencoding() |
---|
37 | n/a | esc = 'surrogateescape' |
---|
38 | n/a | try: |
---|
39 | n/a | ''.encode('utf-8', esc) |
---|
40 | n/a | except LookupError: |
---|
41 | n/a | esc = 'replace' |
---|
42 | n/a | environ = {} |
---|
43 | n/a | |
---|
44 | n/a | # Take the basic environment from native-unicode os.environ. Attempt to |
---|
45 | n/a | # fix up the variables that come from the HTTP request to compensate for |
---|
46 | n/a | # the bytes->unicode decoding step that will already have taken place. |
---|
47 | n/a | for k, v in os.environ.items(): |
---|
48 | n/a | if _needs_transcode(k): |
---|
49 | n/a | |
---|
50 | n/a | # On win32, the os.environ is natively Unicode. Different servers |
---|
51 | n/a | # decode the request bytes using different encodings. |
---|
52 | n/a | if sys.platform == 'win32': |
---|
53 | n/a | software = os.environ.get('SERVER_SOFTWARE', '').lower() |
---|
54 | n/a | |
---|
55 | n/a | # On IIS, the HTTP request will be decoded as UTF-8 as long |
---|
56 | n/a | # as the input is a valid UTF-8 sequence. Otherwise it is |
---|
57 | n/a | # decoded using the system code page (mbcs), with no way to |
---|
58 | n/a | # detect this has happened. Because UTF-8 is the more likely |
---|
59 | n/a | # encoding, and mbcs is inherently unreliable (an mbcs string |
---|
60 | n/a | # that happens to be valid UTF-8 will not be decoded as mbcs) |
---|
61 | n/a | # always recreate the original bytes as UTF-8. |
---|
62 | n/a | if software.startswith('microsoft-iis/'): |
---|
63 | n/a | v = v.encode('utf-8').decode('iso-8859-1') |
---|
64 | n/a | |
---|
65 | n/a | # Apache mod_cgi writes bytes-as-unicode (as if ISO-8859-1) direct |
---|
66 | n/a | # to the Unicode environ. No modification needed. |
---|
67 | n/a | elif software.startswith('apache/'): |
---|
68 | n/a | pass |
---|
69 | n/a | |
---|
70 | n/a | # Python 3's http.server.CGIHTTPRequestHandler decodes |
---|
71 | n/a | # using the urllib.unquote default of UTF-8, amongst other |
---|
72 | n/a | # issues. |
---|
73 | n/a | elif ( |
---|
74 | n/a | software.startswith('simplehttp/') |
---|
75 | n/a | and 'python/3' in software |
---|
76 | n/a | ): |
---|
77 | n/a | v = v.encode('utf-8').decode('iso-8859-1') |
---|
78 | n/a | |
---|
79 | n/a | # For other servers, guess that they have written bytes to |
---|
80 | n/a | # the environ using stdio byte-oriented interfaces, ending up |
---|
81 | n/a | # with the system code page. |
---|
82 | n/a | else: |
---|
83 | n/a | v = v.encode(enc, 'replace').decode('iso-8859-1') |
---|
84 | n/a | |
---|
85 | n/a | # Recover bytes from unicode environ, using surrogate escapes |
---|
86 | n/a | # where available (Python 3.1+). |
---|
87 | n/a | else: |
---|
88 | n/a | v = v.encode(enc, esc).decode('iso-8859-1') |
---|
89 | n/a | |
---|
90 | n/a | environ[k] = v |
---|
91 | n/a | return environ |
---|
92 | n/a | |
---|
93 | n/a | |
---|
94 | n/a | class BaseHandler: |
---|
95 | n/a | """Manage the invocation of a WSGI application""" |
---|
96 | n/a | |
---|
97 | n/a | # Configuration parameters; can override per-subclass or per-instance |
---|
98 | n/a | wsgi_version = (1,0) |
---|
99 | n/a | wsgi_multithread = True |
---|
100 | n/a | wsgi_multiprocess = True |
---|
101 | n/a | wsgi_run_once = False |
---|
102 | n/a | |
---|
103 | n/a | origin_server = True # We are transmitting direct to client |
---|
104 | n/a | http_version = "1.0" # Version that should be used for response |
---|
105 | n/a | server_software = None # String name of server software, if any |
---|
106 | n/a | |
---|
107 | n/a | # os_environ is used to supply configuration from the OS environment: |
---|
108 | n/a | # by default it's a copy of 'os.environ' as of import time, but you can |
---|
109 | n/a | # override this in e.g. your __init__ method. |
---|
110 | n/a | os_environ= read_environ() |
---|
111 | n/a | |
---|
112 | n/a | # Collaborator classes |
---|
113 | n/a | wsgi_file_wrapper = FileWrapper # set to None to disable |
---|
114 | n/a | headers_class = Headers # must be a Headers-like class |
---|
115 | n/a | |
---|
116 | n/a | # Error handling (also per-subclass or per-instance) |
---|
117 | n/a | traceback_limit = None # Print entire traceback to self.get_stderr() |
---|
118 | n/a | error_status = "500 Internal Server Error" |
---|
119 | n/a | error_headers = [('Content-Type','text/plain')] |
---|
120 | n/a | error_body = b"A server error occurred. Please contact the administrator." |
---|
121 | n/a | |
---|
122 | n/a | # State variables (don't mess with these) |
---|
123 | n/a | status = result = None |
---|
124 | n/a | headers_sent = False |
---|
125 | n/a | headers = None |
---|
126 | n/a | bytes_sent = 0 |
---|
127 | n/a | |
---|
128 | n/a | def run(self, application): |
---|
129 | n/a | """Invoke the application""" |
---|
130 | n/a | # Note to self: don't move the close()! Asynchronous servers shouldn't |
---|
131 | n/a | # call close() from finish_response(), so if you close() anywhere but |
---|
132 | n/a | # the double-error branch here, you'll break asynchronous servers by |
---|
133 | n/a | # prematurely closing. Async servers must return from 'run()' without |
---|
134 | n/a | # closing if there might still be output to iterate over. |
---|
135 | n/a | try: |
---|
136 | n/a | self.setup_environ() |
---|
137 | n/a | self.result = application(self.environ, self.start_response) |
---|
138 | n/a | self.finish_response() |
---|
139 | n/a | except: |
---|
140 | n/a | try: |
---|
141 | n/a | self.handle_error() |
---|
142 | n/a | except: |
---|
143 | n/a | # If we get an error handling an error, just give up already! |
---|
144 | n/a | self.close() |
---|
145 | n/a | raise # ...and let the actual server figure it out. |
---|
146 | n/a | |
---|
147 | n/a | |
---|
148 | n/a | def setup_environ(self): |
---|
149 | n/a | """Set up the environment for one request""" |
---|
150 | n/a | |
---|
151 | n/a | env = self.environ = self.os_environ.copy() |
---|
152 | n/a | self.add_cgi_vars() |
---|
153 | n/a | |
---|
154 | n/a | env['wsgi.input'] = self.get_stdin() |
---|
155 | n/a | env['wsgi.errors'] = self.get_stderr() |
---|
156 | n/a | env['wsgi.version'] = self.wsgi_version |
---|
157 | n/a | env['wsgi.run_once'] = self.wsgi_run_once |
---|
158 | n/a | env['wsgi.url_scheme'] = self.get_scheme() |
---|
159 | n/a | env['wsgi.multithread'] = self.wsgi_multithread |
---|
160 | n/a | env['wsgi.multiprocess'] = self.wsgi_multiprocess |
---|
161 | n/a | |
---|
162 | n/a | if self.wsgi_file_wrapper is not None: |
---|
163 | n/a | env['wsgi.file_wrapper'] = self.wsgi_file_wrapper |
---|
164 | n/a | |
---|
165 | n/a | if self.origin_server and self.server_software: |
---|
166 | n/a | env.setdefault('SERVER_SOFTWARE',self.server_software) |
---|
167 | n/a | |
---|
168 | n/a | |
---|
169 | n/a | def finish_response(self): |
---|
170 | n/a | """Send any iterable data, then close self and the iterable |
---|
171 | n/a | |
---|
172 | n/a | Subclasses intended for use in asynchronous servers will |
---|
173 | n/a | want to redefine this method, such that it sets up callbacks |
---|
174 | n/a | in the event loop to iterate over the data, and to call |
---|
175 | n/a | 'self.close()' once the response is finished. |
---|
176 | n/a | """ |
---|
177 | n/a | try: |
---|
178 | n/a | if not self.result_is_file() or not self.sendfile(): |
---|
179 | n/a | for data in self.result: |
---|
180 | n/a | self.write(data) |
---|
181 | n/a | self.finish_content() |
---|
182 | n/a | finally: |
---|
183 | n/a | self.close() |
---|
184 | n/a | |
---|
185 | n/a | |
---|
186 | n/a | def get_scheme(self): |
---|
187 | n/a | """Return the URL scheme being used""" |
---|
188 | n/a | return guess_scheme(self.environ) |
---|
189 | n/a | |
---|
190 | n/a | |
---|
191 | n/a | def set_content_length(self): |
---|
192 | n/a | """Compute Content-Length or switch to chunked encoding if possible""" |
---|
193 | n/a | try: |
---|
194 | n/a | blocks = len(self.result) |
---|
195 | n/a | except (TypeError,AttributeError,NotImplementedError): |
---|
196 | n/a | pass |
---|
197 | n/a | else: |
---|
198 | n/a | if blocks==1: |
---|
199 | n/a | self.headers['Content-Length'] = str(self.bytes_sent) |
---|
200 | n/a | return |
---|
201 | n/a | # XXX Try for chunked encoding if origin server and client is 1.1 |
---|
202 | n/a | |
---|
203 | n/a | |
---|
204 | n/a | def cleanup_headers(self): |
---|
205 | n/a | """Make any necessary header changes or defaults |
---|
206 | n/a | |
---|
207 | n/a | Subclasses can extend this to add other defaults. |
---|
208 | n/a | """ |
---|
209 | n/a | if 'Content-Length' not in self.headers: |
---|
210 | n/a | self.set_content_length() |
---|
211 | n/a | |
---|
212 | n/a | def start_response(self, status, headers,exc_info=None): |
---|
213 | n/a | """'start_response()' callable as specified by PEP 3333""" |
---|
214 | n/a | |
---|
215 | n/a | if exc_info: |
---|
216 | n/a | try: |
---|
217 | n/a | if self.headers_sent: |
---|
218 | n/a | # Re-raise original exception if headers sent |
---|
219 | n/a | raise exc_info[0](exc_info[1]).with_traceback(exc_info[2]) |
---|
220 | n/a | finally: |
---|
221 | n/a | exc_info = None # avoid dangling circular ref |
---|
222 | n/a | elif self.headers is not None: |
---|
223 | n/a | raise AssertionError("Headers already set!") |
---|
224 | n/a | |
---|
225 | n/a | self.status = status |
---|
226 | n/a | self.headers = self.headers_class(headers) |
---|
227 | n/a | status = self._convert_string_type(status, "Status") |
---|
228 | n/a | assert len(status)>=4,"Status must be at least 4 characters" |
---|
229 | n/a | assert status[:3].isdigit(), "Status message must begin w/3-digit code" |
---|
230 | n/a | assert status[3]==" ", "Status message must have a space after code" |
---|
231 | n/a | |
---|
232 | n/a | if __debug__: |
---|
233 | n/a | for name, val in headers: |
---|
234 | n/a | name = self._convert_string_type(name, "Header name") |
---|
235 | n/a | val = self._convert_string_type(val, "Header value") |
---|
236 | n/a | assert not is_hop_by_hop(name),"Hop-by-hop headers not allowed" |
---|
237 | n/a | |
---|
238 | n/a | return self.write |
---|
239 | n/a | |
---|
240 | n/a | def _convert_string_type(self, value, title): |
---|
241 | n/a | """Convert/check value type.""" |
---|
242 | n/a | if type(value) is str: |
---|
243 | n/a | return value |
---|
244 | n/a | raise AssertionError( |
---|
245 | n/a | "{0} must be of type str (got {1})".format(title, repr(value)) |
---|
246 | n/a | ) |
---|
247 | n/a | |
---|
248 | n/a | def send_preamble(self): |
---|
249 | n/a | """Transmit version/status/date/server, via self._write()""" |
---|
250 | n/a | if self.origin_server: |
---|
251 | n/a | if self.client_is_modern(): |
---|
252 | n/a | self._write(('HTTP/%s %s\r\n' % (self.http_version,self.status)).encode('iso-8859-1')) |
---|
253 | n/a | if 'Date' not in self.headers: |
---|
254 | n/a | self._write( |
---|
255 | n/a | ('Date: %s\r\n' % format_date_time(time.time())).encode('iso-8859-1') |
---|
256 | n/a | ) |
---|
257 | n/a | if self.server_software and 'Server' not in self.headers: |
---|
258 | n/a | self._write(('Server: %s\r\n' % self.server_software).encode('iso-8859-1')) |
---|
259 | n/a | else: |
---|
260 | n/a | self._write(('Status: %s\r\n' % self.status).encode('iso-8859-1')) |
---|
261 | n/a | |
---|
262 | n/a | def write(self, data): |
---|
263 | n/a | """'write()' callable as specified by PEP 3333""" |
---|
264 | n/a | |
---|
265 | n/a | assert type(data) is bytes, \ |
---|
266 | n/a | "write() argument must be a bytes instance" |
---|
267 | n/a | |
---|
268 | n/a | if not self.status: |
---|
269 | n/a | raise AssertionError("write() before start_response()") |
---|
270 | n/a | |
---|
271 | n/a | elif not self.headers_sent: |
---|
272 | n/a | # Before the first output, send the stored headers |
---|
273 | n/a | self.bytes_sent = len(data) # make sure we know content-length |
---|
274 | n/a | self.send_headers() |
---|
275 | n/a | else: |
---|
276 | n/a | self.bytes_sent += len(data) |
---|
277 | n/a | |
---|
278 | n/a | # XXX check Content-Length and truncate if too many bytes written? |
---|
279 | n/a | self._write(data) |
---|
280 | n/a | self._flush() |
---|
281 | n/a | |
---|
282 | n/a | |
---|
283 | n/a | def sendfile(self): |
---|
284 | n/a | """Platform-specific file transmission |
---|
285 | n/a | |
---|
286 | n/a | Override this method in subclasses to support platform-specific |
---|
287 | n/a | file transmission. It is only called if the application's |
---|
288 | n/a | return iterable ('self.result') is an instance of |
---|
289 | n/a | 'self.wsgi_file_wrapper'. |
---|
290 | n/a | |
---|
291 | n/a | This method should return a true value if it was able to actually |
---|
292 | n/a | transmit the wrapped file-like object using a platform-specific |
---|
293 | n/a | approach. It should return a false value if normal iteration |
---|
294 | n/a | should be used instead. An exception can be raised to indicate |
---|
295 | n/a | that transmission was attempted, but failed. |
---|
296 | n/a | |
---|
297 | n/a | NOTE: this method should call 'self.send_headers()' if |
---|
298 | n/a | 'self.headers_sent' is false and it is going to attempt direct |
---|
299 | n/a | transmission of the file. |
---|
300 | n/a | """ |
---|
301 | n/a | return False # No platform-specific transmission by default |
---|
302 | n/a | |
---|
303 | n/a | |
---|
304 | n/a | def finish_content(self): |
---|
305 | n/a | """Ensure headers and content have both been sent""" |
---|
306 | n/a | if not self.headers_sent: |
---|
307 | n/a | # Only zero Content-Length if not set by the application (so |
---|
308 | n/a | # that HEAD requests can be satisfied properly, see #3839) |
---|
309 | n/a | self.headers.setdefault('Content-Length', "0") |
---|
310 | n/a | self.send_headers() |
---|
311 | n/a | else: |
---|
312 | n/a | pass # XXX check if content-length was too short? |
---|
313 | n/a | |
---|
314 | n/a | def close(self): |
---|
315 | n/a | """Close the iterable (if needed) and reset all instance vars |
---|
316 | n/a | |
---|
317 | n/a | Subclasses may want to also drop the client connection. |
---|
318 | n/a | """ |
---|
319 | n/a | try: |
---|
320 | n/a | if hasattr(self.result,'close'): |
---|
321 | n/a | self.result.close() |
---|
322 | n/a | finally: |
---|
323 | n/a | self.result = self.headers = self.status = self.environ = None |
---|
324 | n/a | self.bytes_sent = 0; self.headers_sent = False |
---|
325 | n/a | |
---|
326 | n/a | |
---|
327 | n/a | def send_headers(self): |
---|
328 | n/a | """Transmit headers to the client, via self._write()""" |
---|
329 | n/a | self.cleanup_headers() |
---|
330 | n/a | self.headers_sent = True |
---|
331 | n/a | if not self.origin_server or self.client_is_modern(): |
---|
332 | n/a | self.send_preamble() |
---|
333 | n/a | self._write(bytes(self.headers)) |
---|
334 | n/a | |
---|
335 | n/a | |
---|
336 | n/a | def result_is_file(self): |
---|
337 | n/a | """True if 'self.result' is an instance of 'self.wsgi_file_wrapper'""" |
---|
338 | n/a | wrapper = self.wsgi_file_wrapper |
---|
339 | n/a | return wrapper is not None and isinstance(self.result,wrapper) |
---|
340 | n/a | |
---|
341 | n/a | |
---|
342 | n/a | def client_is_modern(self): |
---|
343 | n/a | """True if client can accept status and headers""" |
---|
344 | n/a | return self.environ['SERVER_PROTOCOL'].upper() != 'HTTP/0.9' |
---|
345 | n/a | |
---|
346 | n/a | |
---|
347 | n/a | def log_exception(self,exc_info): |
---|
348 | n/a | """Log the 'exc_info' tuple in the server log |
---|
349 | n/a | |
---|
350 | n/a | Subclasses may override to retarget the output or change its format. |
---|
351 | n/a | """ |
---|
352 | n/a | try: |
---|
353 | n/a | from traceback import print_exception |
---|
354 | n/a | stderr = self.get_stderr() |
---|
355 | n/a | print_exception( |
---|
356 | n/a | exc_info[0], exc_info[1], exc_info[2], |
---|
357 | n/a | self.traceback_limit, stderr |
---|
358 | n/a | ) |
---|
359 | n/a | stderr.flush() |
---|
360 | n/a | finally: |
---|
361 | n/a | exc_info = None |
---|
362 | n/a | |
---|
363 | n/a | def handle_error(self): |
---|
364 | n/a | """Log current error, and send error output to client if possible""" |
---|
365 | n/a | self.log_exception(sys.exc_info()) |
---|
366 | n/a | if not self.headers_sent: |
---|
367 | n/a | self.result = self.error_output(self.environ, self.start_response) |
---|
368 | n/a | self.finish_response() |
---|
369 | n/a | # XXX else: attempt advanced recovery techniques for HTML or text? |
---|
370 | n/a | |
---|
371 | n/a | def error_output(self, environ, start_response): |
---|
372 | n/a | """WSGI mini-app to create error output |
---|
373 | n/a | |
---|
374 | n/a | By default, this just uses the 'error_status', 'error_headers', |
---|
375 | n/a | and 'error_body' attributes to generate an output page. It can |
---|
376 | n/a | be overridden in a subclass to dynamically generate diagnostics, |
---|
377 | n/a | choose an appropriate message for the user's preferred language, etc. |
---|
378 | n/a | |
---|
379 | n/a | Note, however, that it's not recommended from a security perspective to |
---|
380 | n/a | spit out diagnostics to any old user; ideally, you should have to do |
---|
381 | n/a | something special to enable diagnostic output, which is why we don't |
---|
382 | n/a | include any here! |
---|
383 | n/a | """ |
---|
384 | n/a | start_response(self.error_status,self.error_headers[:],sys.exc_info()) |
---|
385 | n/a | return [self.error_body] |
---|
386 | n/a | |
---|
387 | n/a | |
---|
388 | n/a | # Pure abstract methods; *must* be overridden in subclasses |
---|
389 | n/a | |
---|
390 | n/a | def _write(self,data): |
---|
391 | n/a | """Override in subclass to buffer data for send to client |
---|
392 | n/a | |
---|
393 | n/a | It's okay if this method actually transmits the data; BaseHandler |
---|
394 | n/a | just separates write and flush operations for greater efficiency |
---|
395 | n/a | when the underlying system actually has such a distinction. |
---|
396 | n/a | """ |
---|
397 | n/a | raise NotImplementedError |
---|
398 | n/a | |
---|
399 | n/a | def _flush(self): |
---|
400 | n/a | """Override in subclass to force sending of recent '_write()' calls |
---|
401 | n/a | |
---|
402 | n/a | It's okay if this method is a no-op (i.e., if '_write()' actually |
---|
403 | n/a | sends the data. |
---|
404 | n/a | """ |
---|
405 | n/a | raise NotImplementedError |
---|
406 | n/a | |
---|
407 | n/a | def get_stdin(self): |
---|
408 | n/a | """Override in subclass to return suitable 'wsgi.input'""" |
---|
409 | n/a | raise NotImplementedError |
---|
410 | n/a | |
---|
411 | n/a | def get_stderr(self): |
---|
412 | n/a | """Override in subclass to return suitable 'wsgi.errors'""" |
---|
413 | n/a | raise NotImplementedError |
---|
414 | n/a | |
---|
415 | n/a | def add_cgi_vars(self): |
---|
416 | n/a | """Override in subclass to insert CGI variables in 'self.environ'""" |
---|
417 | n/a | raise NotImplementedError |
---|
418 | n/a | |
---|
419 | n/a | |
---|
420 | n/a | class SimpleHandler(BaseHandler): |
---|
421 | n/a | """Handler that's just initialized with streams, environment, etc. |
---|
422 | n/a | |
---|
423 | n/a | This handler subclass is intended for synchronous HTTP/1.0 origin servers, |
---|
424 | n/a | and handles sending the entire response output, given the correct inputs. |
---|
425 | n/a | |
---|
426 | n/a | Usage:: |
---|
427 | n/a | |
---|
428 | n/a | handler = SimpleHandler( |
---|
429 | n/a | inp,out,err,env, multithread=False, multiprocess=True |
---|
430 | n/a | ) |
---|
431 | n/a | handler.run(app)""" |
---|
432 | n/a | |
---|
433 | n/a | def __init__(self,stdin,stdout,stderr,environ, |
---|
434 | n/a | multithread=True, multiprocess=False |
---|
435 | n/a | ): |
---|
436 | n/a | self.stdin = stdin |
---|
437 | n/a | self.stdout = stdout |
---|
438 | n/a | self.stderr = stderr |
---|
439 | n/a | self.base_env = environ |
---|
440 | n/a | self.wsgi_multithread = multithread |
---|
441 | n/a | self.wsgi_multiprocess = multiprocess |
---|
442 | n/a | |
---|
443 | n/a | def get_stdin(self): |
---|
444 | n/a | return self.stdin |
---|
445 | n/a | |
---|
446 | n/a | def get_stderr(self): |
---|
447 | n/a | return self.stderr |
---|
448 | n/a | |
---|
449 | n/a | def add_cgi_vars(self): |
---|
450 | n/a | self.environ.update(self.base_env) |
---|
451 | n/a | |
---|
452 | n/a | def _write(self,data): |
---|
453 | n/a | result = self.stdout.write(data) |
---|
454 | n/a | if result is None or result == len(data): |
---|
455 | n/a | return |
---|
456 | n/a | from warnings import warn |
---|
457 | n/a | warn("SimpleHandler.stdout.write() should not do partial writes", |
---|
458 | n/a | DeprecationWarning) |
---|
459 | n/a | while True: |
---|
460 | n/a | data = data[result:] |
---|
461 | n/a | if not data: |
---|
462 | n/a | break |
---|
463 | n/a | result = self.stdout.write(data) |
---|
464 | n/a | |
---|
465 | n/a | def _flush(self): |
---|
466 | n/a | self.stdout.flush() |
---|
467 | n/a | self._flush = self.stdout.flush |
---|
468 | n/a | |
---|
469 | n/a | |
---|
470 | n/a | class BaseCGIHandler(SimpleHandler): |
---|
471 | n/a | |
---|
472 | n/a | """CGI-like systems using input/output/error streams and environ mapping |
---|
473 | n/a | |
---|
474 | n/a | Usage:: |
---|
475 | n/a | |
---|
476 | n/a | handler = BaseCGIHandler(inp,out,err,env) |
---|
477 | n/a | handler.run(app) |
---|
478 | n/a | |
---|
479 | n/a | This handler class is useful for gateway protocols like ReadyExec and |
---|
480 | n/a | FastCGI, that have usable input/output/error streams and an environment |
---|
481 | n/a | mapping. It's also the base class for CGIHandler, which just uses |
---|
482 | n/a | sys.stdin, os.environ, and so on. |
---|
483 | n/a | |
---|
484 | n/a | The constructor also takes keyword arguments 'multithread' and |
---|
485 | n/a | 'multiprocess' (defaulting to 'True' and 'False' respectively) to control |
---|
486 | n/a | the configuration sent to the application. It sets 'origin_server' to |
---|
487 | n/a | False (to enable CGI-like output), and assumes that 'wsgi.run_once' is |
---|
488 | n/a | False. |
---|
489 | n/a | """ |
---|
490 | n/a | |
---|
491 | n/a | origin_server = False |
---|
492 | n/a | |
---|
493 | n/a | |
---|
494 | n/a | class CGIHandler(BaseCGIHandler): |
---|
495 | n/a | |
---|
496 | n/a | """CGI-based invocation via sys.stdin/stdout/stderr and os.environ |
---|
497 | n/a | |
---|
498 | n/a | Usage:: |
---|
499 | n/a | |
---|
500 | n/a | CGIHandler().run(app) |
---|
501 | n/a | |
---|
502 | n/a | The difference between this class and BaseCGIHandler is that it always |
---|
503 | n/a | uses 'wsgi.run_once' of 'True', 'wsgi.multithread' of 'False', and |
---|
504 | n/a | 'wsgi.multiprocess' of 'True'. It does not take any initialization |
---|
505 | n/a | parameters, but always uses 'sys.stdin', 'os.environ', and friends. |
---|
506 | n/a | |
---|
507 | n/a | If you need to override any of these parameters, use BaseCGIHandler |
---|
508 | n/a | instead. |
---|
509 | n/a | """ |
---|
510 | n/a | |
---|
511 | n/a | wsgi_run_once = True |
---|
512 | n/a | # Do not allow os.environ to leak between requests in Google App Engine |
---|
513 | n/a | # and other multi-run CGI use cases. This is not easily testable. |
---|
514 | n/a | # See http://bugs.python.org/issue7250 |
---|
515 | n/a | os_environ = {} |
---|
516 | n/a | |
---|
517 | n/a | def __init__(self): |
---|
518 | n/a | BaseCGIHandler.__init__( |
---|
519 | n/a | self, sys.stdin.buffer, sys.stdout.buffer, sys.stderr, |
---|
520 | n/a | read_environ(), multithread=False, multiprocess=True |
---|
521 | n/a | ) |
---|
522 | n/a | |
---|
523 | n/a | |
---|
524 | n/a | class IISCGIHandler(BaseCGIHandler): |
---|
525 | n/a | """CGI-based invocation with workaround for IIS path bug |
---|
526 | n/a | |
---|
527 | n/a | This handler should be used in preference to CGIHandler when deploying on |
---|
528 | n/a | Microsoft IIS without having set the config allowPathInfo option (IIS>=7) |
---|
529 | n/a | or metabase allowPathInfoForScriptMappings (IIS<7). |
---|
530 | n/a | """ |
---|
531 | n/a | wsgi_run_once = True |
---|
532 | n/a | os_environ = {} |
---|
533 | n/a | |
---|
534 | n/a | # By default, IIS gives a PATH_INFO that duplicates the SCRIPT_NAME at |
---|
535 | n/a | # the front, causing problems for WSGI applications that wish to implement |
---|
536 | n/a | # routing. This handler strips any such duplicated path. |
---|
537 | n/a | |
---|
538 | n/a | # IIS can be configured to pass the correct PATH_INFO, but this causes |
---|
539 | n/a | # another bug where PATH_TRANSLATED is wrong. Luckily this variable is |
---|
540 | n/a | # rarely used and is not guaranteed by WSGI. On IIS<7, though, the |
---|
541 | n/a | # setting can only be made on a vhost level, affecting all other script |
---|
542 | n/a | # mappings, many of which break when exposed to the PATH_TRANSLATED bug. |
---|
543 | n/a | # For this reason IIS<7 is almost never deployed with the fix. (Even IIS7 |
---|
544 | n/a | # rarely uses it because there is still no UI for it.) |
---|
545 | n/a | |
---|
546 | n/a | # There is no way for CGI code to tell whether the option was set, so a |
---|
547 | n/a | # separate handler class is provided. |
---|
548 | n/a | def __init__(self): |
---|
549 | n/a | environ= read_environ() |
---|
550 | n/a | path = environ.get('PATH_INFO', '') |
---|
551 | n/a | script = environ.get('SCRIPT_NAME', '') |
---|
552 | n/a | if (path+'/').startswith(script+'/'): |
---|
553 | n/a | environ['PATH_INFO'] = path[len(script):] |
---|
554 | n/a | BaseCGIHandler.__init__( |
---|
555 | n/a | self, sys.stdin.buffer, sys.stdout.buffer, sys.stderr, |
---|
556 | n/a | environ, multithread=False, multiprocess=True |
---|
557 | n/a | ) |
---|