mirror of
https://github.com/python/cpython.git
synced 2025-09-20 15:40:32 +00:00

svn+ssh://pythondev@svn.python.org/python/branches/p3yk ................ r55636 | neal.norwitz | 2007-05-29 00:06:39 -0700 (Tue, 29 May 2007) | 149 lines Merged revisions 55506-55635 via svnmerge from svn+ssh://pythondev@svn.python.org/python/trunk ........ r55507 | georg.brandl | 2007-05-22 07:28:17 -0700 (Tue, 22 May 2007) | 2 lines Remove the "panel" module doc file which has been ignored since 1994. ........ r55522 | mark.hammond | 2007-05-22 19:04:28 -0700 (Tue, 22 May 2007) | 4 lines Remove definition of PY_UNICODE_TYPE from pyconfig.h, allowing the definition in unicodeobject.h to be used, giving us the desired wchar_t in place of 'unsigned short'. As discussed on python-dev. ........ r55525 | neal.norwitz | 2007-05-22 23:35:32 -0700 (Tue, 22 May 2007) | 6 lines Add -3 option to the interpreter to warn about features that are deprecated and will be changed/removed in Python 3.0. This patch is mostly from Anthony. I tweaked some format and added a little doc. ........ r55527 | neal.norwitz | 2007-05-22 23:57:35 -0700 (Tue, 22 May 2007) | 1 line Whitespace cleanup ........ r55528 | neal.norwitz | 2007-05-22 23:58:36 -0700 (Tue, 22 May 2007) | 1 line Add a bunch more deprecation warnings for builtins that are going away in 3.0 ........ r55549 | georg.brandl | 2007-05-24 09:49:29 -0700 (Thu, 24 May 2007) | 2 lines shlex.split() now has an optional "posix" parameter. ........ r55550 | georg.brandl | 2007-05-24 10:33:33 -0700 (Thu, 24 May 2007) | 2 lines Fix parameter passing. ........ r55555 | facundo.batista | 2007-05-24 10:50:54 -0700 (Thu, 24 May 2007) | 6 lines Added an optional timeout parameter to urllib.ftpwrapper, with tests (for this and a basic one, because there weren't any). Changed also NEWS, but didn't find documentation for this function, assumed it wasn't public... ........ r55563 | facundo.batista | 2007-05-24 13:01:59 -0700 (Thu, 24 May 2007) | 4 lines Removed the .recv() in the test, is not necessary, and was causing problems that didn't have anything to do with was actually being tested... ........ r55564 | facundo.batista | 2007-05-24 13:51:19 -0700 (Thu, 24 May 2007) | 5 lines Let's see if reading exactly what is written allow this live test to pass (now I know why there were so few tests in ftp, http, etc, :( ). ........ r55567 | facundo.batista | 2007-05-24 20:10:28 -0700 (Thu, 24 May 2007) | 4 lines Trying to make the tests work in Windows and Solaris, everywhere else just works ........ r55568 | facundo.batista | 2007-05-24 20:47:19 -0700 (Thu, 24 May 2007) | 4 lines Fixing stupid error, and introducing a sleep, to see if the other thread is awakened and finish sending data. ........ r55569 | facundo.batista | 2007-05-24 21:20:22 -0700 (Thu, 24 May 2007) | 4 lines Commenting out the tests until find out who can test them in one of the problematic enviroments. ........ r55570 | neal.norwitz | 2007-05-24 22:13:40 -0700 (Thu, 24 May 2007) | 2 lines Get test passing again by commenting out the reference to the test class. ........ r55575 | vinay.sajip | 2007-05-25 00:05:59 -0700 (Fri, 25 May 2007) | 1 line Updated docstring for SysLogHandler (#1720726). ........ r55576 | vinay.sajip | 2007-05-25 00:06:55 -0700 (Fri, 25 May 2007) | 1 line Updated documentation for SysLogHandler (#1720726). ........ r55592 | brett.cannon | 2007-05-25 13:17:15 -0700 (Fri, 25 May 2007) | 3 lines Remove direct call's to file's constructor and replace them with calls to open() as ths is considered best practice. ........ r55601 | kristjan.jonsson | 2007-05-26 12:19:50 -0700 (Sat, 26 May 2007) | 1 line Remove the rgbimgmodule from PCBuild8 ........ r55602 | kristjan.jonsson | 2007-05-26 12:31:39 -0700 (Sat, 26 May 2007) | 1 line Include <windows.h> after python.h, so that WINNT is properly set before windows.h is included. Fixes warnings in PC builds. ........ r55603 | walter.doerwald | 2007-05-26 14:04:13 -0700 (Sat, 26 May 2007) | 2 lines Fix typo. ........ r55604 | peter.astrand | 2007-05-26 15:18:20 -0700 (Sat, 26 May 2007) | 1 line Applied patch 1669481, slightly modified: Support close_fds on Win32 ........ r55606 | neal.norwitz | 2007-05-26 21:08:54 -0700 (Sat, 26 May 2007) | 2 lines Add the new function object attribute names from py3k. ........ r55617 | lars.gustaebel | 2007-05-27 12:49:30 -0700 (Sun, 27 May 2007) | 20 lines Added errors argument to TarFile class that allows the user to specify an error handling scheme for character conversion. Additional scheme "utf-8" in read mode. Unicode input filenames are now supported by design. The values of the pax_headers dictionary are now limited to unicode objects. Fixed: The prefix field is no longer used in PAX_FORMAT (in conformance with POSIX). Fixed: In read mode use a possible pax header size field. Fixed: Strip trailing slashes from pax header name values. Fixed: Give values in user-specified pax_headers precedence when writing. Added unicode tests. Added pax/regtype4 member to testtar.tar all possible number fields in a pax header. Added two chapters to the documentation about the different formats tarfile.py supports and how unicode issues are handled. ........ r55618 | raymond.hettinger | 2007-05-27 22:23:22 -0700 (Sun, 27 May 2007) | 1 line Explain when groupby() issues a new group. ........ r55634 | martin.v.loewis | 2007-05-28 21:01:29 -0700 (Mon, 28 May 2007) | 2 lines Test pre-commit hook for a link to a .py file. ........ r55635 | martin.v.loewis | 2007-05-28 21:02:03 -0700 (Mon, 28 May 2007) | 2 lines Revert 55634. ........ ................ r55639 | neal.norwitz | 2007-05-29 00:58:11 -0700 (Tue, 29 May 2007) | 1 line Remove sys.exc_{type,exc_value,exc_traceback} ................ r55641 | neal.norwitz | 2007-05-29 01:03:50 -0700 (Tue, 29 May 2007) | 1 line Missed one sys.exc_type. I wonder why exc_{value,traceback} were already gone ................ r55642 | neal.norwitz | 2007-05-29 01:08:33 -0700 (Tue, 29 May 2007) | 1 line Missed more doc for sys.exc_* attrs. ................ r55643 | neal.norwitz | 2007-05-29 01:18:19 -0700 (Tue, 29 May 2007) | 1 line Remove sys.exc_clear() ................ r55665 | guido.van.rossum | 2007-05-29 19:45:43 -0700 (Tue, 29 May 2007) | 4 lines Make None, True, False keywords. We can now also delete all the other places that explicitly forbid assignment to None, but I'm not going to bother right now. ................ r55666 | guido.van.rossum | 2007-05-29 20:01:51 -0700 (Tue, 29 May 2007) | 3 lines Found another place that needs check for forbidden names. Fixed test_syntax.py accordingly (it helped me find that one). ................ r55668 | guido.van.rossum | 2007-05-29 20:41:48 -0700 (Tue, 29 May 2007) | 2 lines Mark None, True, False as keywords. ................ r55673 | neal.norwitz | 2007-05-29 23:28:25 -0700 (Tue, 29 May 2007) | 3 lines Get the dis module working on modules again after changing dicts to not return lists and also new-style classes. Add a test. ................ r55674 | neal.norwitz | 2007-05-29 23:35:45 -0700 (Tue, 29 May 2007) | 1 line Umm, it helps to add the module that the test uses ................ r55675 | neal.norwitz | 2007-05-29 23:53:05 -0700 (Tue, 29 May 2007) | 4 lines Try to fix up all the other places that were assigning to True/False. There's at least one more problem in test.test_xmlrpc. I have other changes in that file and that should be fixed soon (I hope). ................ r55679 | neal.norwitz | 2007-05-30 00:31:55 -0700 (Wed, 30 May 2007) | 1 line Fix up another place that was assigning to True/False. ................ r55688 | brett.cannon | 2007-05-30 14:19:47 -0700 (Wed, 30 May 2007) | 2 lines Ditch MimeWriter. ................ r55692 | brett.cannon | 2007-05-30 14:52:00 -0700 (Wed, 30 May 2007) | 2 lines Remove the mimify module. ................ r55707 | guido.van.rossum | 2007-05-31 05:08:45 -0700 (Thu, 31 May 2007) | 2 lines Backport the addition of show_code() to dis.py -- it's too handy. ................ r55708 | guido.van.rossum | 2007-05-31 06:22:57 -0700 (Thu, 31 May 2007) | 7 lines Fix a fairly long-standing bug in the check for assignment to None (and other keywords, these days). In 2.5, you could write foo(None=1) without getting a SyntaxError (although foo()'s definition would have to use **kwds to avoid getting a runtime error complaining about an unknown keyword of course). This ought to be backported to 2.5.2 or at least 2.6. ................ r55724 | brett.cannon | 2007-05-31 19:32:41 -0700 (Thu, 31 May 2007) | 2 lines Remove the cfmfile. ................ r55727 | neal.norwitz | 2007-05-31 22:19:44 -0700 (Thu, 31 May 2007) | 1 line Remove reload() builtin. ................ r55729 | neal.norwitz | 2007-05-31 22:51:30 -0700 (Thu, 31 May 2007) | 59 lines Merged revisions 55636-55728 via svnmerge from svn+ssh://pythondev@svn.python.org/python/trunk ........ r55637 | georg.brandl | 2007-05-29 00:16:47 -0700 (Tue, 29 May 2007) | 2 lines Fix rst markup. ........ r55638 | neal.norwitz | 2007-05-29 00:51:39 -0700 (Tue, 29 May 2007) | 1 line Fix typo in doc ........ r55671 | neal.norwitz | 2007-05-29 21:53:41 -0700 (Tue, 29 May 2007) | 1 line Fix indentation (whitespace only). ........ r55676 | thomas.heller | 2007-05-29 23:58:30 -0700 (Tue, 29 May 2007) | 1 line Fix compiler warnings. ........ r55677 | thomas.heller | 2007-05-30 00:01:25 -0700 (Wed, 30 May 2007) | 2 lines Correct the name of a field in the WIN32_FIND_DATAA and WIN32_FIND_DATAW structures. Closes bug #1726026. ........ r55686 | brett.cannon | 2007-05-30 13:46:26 -0700 (Wed, 30 May 2007) | 2 lines Have MimeWriter raise a DeprecationWarning as per PEP 4 and its documentation. ........ r55690 | brett.cannon | 2007-05-30 14:48:58 -0700 (Wed, 30 May 2007) | 3 lines Have mimify raise a DeprecationWarning. The docs and PEP 4 have listed the module as deprecated for a while. ........ r55696 | brett.cannon | 2007-05-30 15:24:28 -0700 (Wed, 30 May 2007) | 2 lines Have md5 raise a DeprecationWarning as per PEP 4. ........ r55705 | neal.norwitz | 2007-05-30 21:14:22 -0700 (Wed, 30 May 2007) | 1 line Add some spaces in the example code. ........ r55716 | brett.cannon | 2007-05-31 12:20:00 -0700 (Thu, 31 May 2007) | 2 lines Have the sha module raise a DeprecationWarning as specified in PEP 4. ........ r55719 | brett.cannon | 2007-05-31 12:40:42 -0700 (Thu, 31 May 2007) | 2 lines Cause buildtools to raise a DeprecationWarning. ........ r55721 | brett.cannon | 2007-05-31 13:01:11 -0700 (Thu, 31 May 2007) | 2 lines Have cfmfile raise a DeprecationWarning as per PEP 4. ........ r55726 | neal.norwitz | 2007-05-31 21:56:47 -0700 (Thu, 31 May 2007) | 1 line Mail if there is an installation failure. ........ ................ r55730 | neal.norwitz | 2007-05-31 23:22:07 -0700 (Thu, 31 May 2007) | 2 lines Remove the code that was missed in rev 55303. ................ r55738 | neal.norwitz | 2007-06-01 19:10:43 -0700 (Fri, 01 Jun 2007) | 1 line Fix doc breakage ................ r55741 | neal.norwitz | 2007-06-02 00:41:58 -0700 (Sat, 02 Jun 2007) | 1 line Remove timing module (plus some remnants of other modules). ................ r55742 | neal.norwitz | 2007-06-02 00:51:44 -0700 (Sat, 02 Jun 2007) | 1 line Remove posixfile module (plus some remnants of other modules). ................ r55744 | neal.norwitz | 2007-06-02 10:18:56 -0700 (Sat, 02 Jun 2007) | 1 line Fix doc breakage. ................ r55745 | neal.norwitz | 2007-06-02 11:32:16 -0700 (Sat, 02 Jun 2007) | 1 line Make a whatsnew 3.0 template. ................ r55754 | neal.norwitz | 2007-06-03 23:24:18 -0700 (Sun, 03 Jun 2007) | 1 line SF #1730441, os._execvpe raises UnboundLocal due to new try/except semantics ................ r55755 | neal.norwitz | 2007-06-03 23:26:00 -0700 (Sun, 03 Jun 2007) | 1 line Get rid of extra whitespace ................ r55794 | guido.van.rossum | 2007-06-06 15:29:22 -0700 (Wed, 06 Jun 2007) | 3 lines Make this compile in GCC 2.96, which does not allow interspersing declarations and code. ................
475 lines
15 KiB
Python
475 lines
15 KiB
Python
"""Base classes for server/gateway implementations"""
|
|
|
|
from types import StringType
|
|
from .util import FileWrapper, guess_scheme, is_hop_by_hop
|
|
from .headers import Headers
|
|
|
|
import sys, os, time
|
|
|
|
__all__ = ['BaseHandler', 'SimpleHandler', 'BaseCGIHandler', 'CGIHandler']
|
|
|
|
# Weekday and month names for HTTP date/time formatting; always English!
|
|
_weekdayname = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
|
|
_monthname = [None, # Dummy so we can use 1-based month numbers
|
|
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
|
|
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
|
|
|
|
def format_date_time(timestamp):
|
|
year, month, day, hh, mm, ss, wd, y, z = time.gmtime(timestamp)
|
|
return "%s, %02d %3s %4d %02d:%02d:%02d GMT" % (
|
|
_weekdayname[wd], day, _monthname[month], year, hh, mm, ss
|
|
)
|
|
|
|
|
|
|
|
class BaseHandler:
|
|
"""Manage the invocation of a WSGI application"""
|
|
|
|
# Configuration parameters; can override per-subclass or per-instance
|
|
wsgi_version = (1,0)
|
|
wsgi_multithread = True
|
|
wsgi_multiprocess = True
|
|
wsgi_run_once = False
|
|
|
|
origin_server = True # We are transmitting direct to client
|
|
http_version = "1.0" # Version that should be used for response
|
|
server_software = None # String name of server software, if any
|
|
|
|
# os_environ is used to supply configuration from the OS environment:
|
|
# by default it's a copy of 'os.environ' as of import time, but you can
|
|
# override this in e.g. your __init__ method.
|
|
os_environ = dict(os.environ.items())
|
|
|
|
# Collaborator classes
|
|
wsgi_file_wrapper = FileWrapper # set to None to disable
|
|
headers_class = Headers # must be a Headers-like class
|
|
|
|
# Error handling (also per-subclass or per-instance)
|
|
traceback_limit = None # Print entire traceback to self.get_stderr()
|
|
error_status = "500 Dude, this is whack!"
|
|
error_headers = [('Content-Type','text/plain')]
|
|
error_body = "A server error occurred. Please contact the administrator."
|
|
|
|
# State variables (don't mess with these)
|
|
status = result = None
|
|
headers_sent = False
|
|
headers = None
|
|
bytes_sent = 0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def run(self, application):
|
|
"""Invoke the application"""
|
|
# Note to self: don't move the close()! Asynchronous servers shouldn't
|
|
# call close() from finish_response(), so if you close() anywhere but
|
|
# the double-error branch here, you'll break asynchronous servers by
|
|
# prematurely closing. Async servers must return from 'run()' without
|
|
# closing if there might still be output to iterate over.
|
|
try:
|
|
self.setup_environ()
|
|
self.result = application(self.environ, self.start_response)
|
|
self.finish_response()
|
|
except:
|
|
try:
|
|
self.handle_error()
|
|
except:
|
|
# If we get an error handling an error, just give up already!
|
|
self.close()
|
|
raise # ...and let the actual server figure it out.
|
|
|
|
|
|
def setup_environ(self):
|
|
"""Set up the environment for one request"""
|
|
|
|
env = self.environ = self.os_environ.copy()
|
|
self.add_cgi_vars()
|
|
|
|
env['wsgi.input'] = self.get_stdin()
|
|
env['wsgi.errors'] = self.get_stderr()
|
|
env['wsgi.version'] = self.wsgi_version
|
|
env['wsgi.run_once'] = self.wsgi_run_once
|
|
env['wsgi.url_scheme'] = self.get_scheme()
|
|
env['wsgi.multithread'] = self.wsgi_multithread
|
|
env['wsgi.multiprocess'] = self.wsgi_multiprocess
|
|
|
|
if self.wsgi_file_wrapper is not None:
|
|
env['wsgi.file_wrapper'] = self.wsgi_file_wrapper
|
|
|
|
if self.origin_server and self.server_software:
|
|
env.setdefault('SERVER_SOFTWARE',self.server_software)
|
|
|
|
|
|
def finish_response(self):
|
|
"""Send any iterable data, then close self and the iterable
|
|
|
|
Subclasses intended for use in asynchronous servers will
|
|
want to redefine this method, such that it sets up callbacks
|
|
in the event loop to iterate over the data, and to call
|
|
'self.close()' once the response is finished.
|
|
"""
|
|
if not self.result_is_file() or not self.sendfile():
|
|
for data in self.result:
|
|
self.write(data)
|
|
self.finish_content()
|
|
self.close()
|
|
|
|
|
|
def get_scheme(self):
|
|
"""Return the URL scheme being used"""
|
|
return guess_scheme(self.environ)
|
|
|
|
|
|
def set_content_length(self):
|
|
"""Compute Content-Length or switch to chunked encoding if possible"""
|
|
try:
|
|
blocks = len(self.result)
|
|
except (TypeError,AttributeError,NotImplementedError):
|
|
pass
|
|
else:
|
|
if blocks==1:
|
|
self.headers['Content-Length'] = str(self.bytes_sent)
|
|
return
|
|
# XXX Try for chunked encoding if origin server and client is 1.1
|
|
|
|
|
|
def cleanup_headers(self):
|
|
"""Make any necessary header changes or defaults
|
|
|
|
Subclasses can extend this to add other defaults.
|
|
"""
|
|
if 'Content-Length' not in self.headers:
|
|
self.set_content_length()
|
|
|
|
def start_response(self, status, headers,exc_info=None):
|
|
"""'start_response()' callable as specified by PEP 333"""
|
|
|
|
if exc_info:
|
|
try:
|
|
if self.headers_sent:
|
|
# Re-raise original exception if headers sent
|
|
raise exc_info[0], exc_info[1], exc_info[2]
|
|
finally:
|
|
exc_info = None # avoid dangling circular ref
|
|
elif self.headers is not None:
|
|
raise AssertionError("Headers already set!")
|
|
|
|
assert type(status) is StringType,"Status must be a string"
|
|
assert len(status)>=4,"Status must be at least 4 characters"
|
|
assert int(status[:3]),"Status message must begin w/3-digit code"
|
|
assert status[3]==" ", "Status message must have a space after code"
|
|
if __debug__:
|
|
for name,val in headers:
|
|
assert type(name) is StringType,"Header names must be strings"
|
|
assert type(val) is StringType,"Header values must be strings"
|
|
assert not is_hop_by_hop(name),"Hop-by-hop headers not allowed"
|
|
self.status = status
|
|
self.headers = self.headers_class(headers)
|
|
return self.write
|
|
|
|
|
|
def send_preamble(self):
|
|
"""Transmit version/status/date/server, via self._write()"""
|
|
if self.origin_server:
|
|
if self.client_is_modern():
|
|
self._write('HTTP/%s %s\r\n' % (self.http_version,self.status))
|
|
if 'Date' not in self.headers:
|
|
self._write(
|
|
'Date: %s\r\n' % format_date_time(time.time())
|
|
)
|
|
if self.server_software and 'Server' not in self.headers:
|
|
self._write('Server: %s\r\n' % self.server_software)
|
|
else:
|
|
self._write('Status: %s\r\n' % self.status)
|
|
|
|
def write(self, data):
|
|
"""'write()' callable as specified by PEP 333"""
|
|
|
|
assert type(data) is StringType,"write() argument must be string"
|
|
|
|
if not self.status:
|
|
raise AssertionError("write() before start_response()")
|
|
|
|
elif not self.headers_sent:
|
|
# Before the first output, send the stored headers
|
|
self.bytes_sent = len(data) # make sure we know content-length
|
|
self.send_headers()
|
|
else:
|
|
self.bytes_sent += len(data)
|
|
|
|
# XXX check Content-Length and truncate if too many bytes written?
|
|
self._write(data)
|
|
self._flush()
|
|
|
|
|
|
def sendfile(self):
|
|
"""Platform-specific file transmission
|
|
|
|
Override this method in subclasses to support platform-specific
|
|
file transmission. It is only called if the application's
|
|
return iterable ('self.result') is an instance of
|
|
'self.wsgi_file_wrapper'.
|
|
|
|
This method should return a true value if it was able to actually
|
|
transmit the wrapped file-like object using a platform-specific
|
|
approach. It should return a false value if normal iteration
|
|
should be used instead. An exception can be raised to indicate
|
|
that transmission was attempted, but failed.
|
|
|
|
NOTE: this method should call 'self.send_headers()' if
|
|
'self.headers_sent' is false and it is going to attempt direct
|
|
transmission of the file.
|
|
"""
|
|
return False # No platform-specific transmission by default
|
|
|
|
|
|
def finish_content(self):
|
|
"""Ensure headers and content have both been sent"""
|
|
if not self.headers_sent:
|
|
self.headers['Content-Length'] = "0"
|
|
self.send_headers()
|
|
else:
|
|
pass # XXX check if content-length was too short?
|
|
|
|
def close(self):
|
|
"""Close the iterable (if needed) and reset all instance vars
|
|
|
|
Subclasses may want to also drop the client connection.
|
|
"""
|
|
try:
|
|
if hasattr(self.result,'close'):
|
|
self.result.close()
|
|
finally:
|
|
self.result = self.headers = self.status = self.environ = None
|
|
self.bytes_sent = 0; self.headers_sent = False
|
|
|
|
|
|
def send_headers(self):
|
|
"""Transmit headers to the client, via self._write()"""
|
|
self.cleanup_headers()
|
|
self.headers_sent = True
|
|
if not self.origin_server or self.client_is_modern():
|
|
self.send_preamble()
|
|
self._write(str(self.headers))
|
|
|
|
|
|
def result_is_file(self):
|
|
"""True if 'self.result' is an instance of 'self.wsgi_file_wrapper'"""
|
|
wrapper = self.wsgi_file_wrapper
|
|
return wrapper is not None and isinstance(self.result,wrapper)
|
|
|
|
|
|
def client_is_modern(self):
|
|
"""True if client can accept status and headers"""
|
|
return self.environ['SERVER_PROTOCOL'].upper() != 'HTTP/0.9'
|
|
|
|
|
|
def log_exception(self,exc_info):
|
|
"""Log the 'exc_info' tuple in the server log
|
|
|
|
Subclasses may override to retarget the output or change its format.
|
|
"""
|
|
try:
|
|
from traceback import print_exception
|
|
stderr = self.get_stderr()
|
|
print_exception(
|
|
exc_info[0], exc_info[1], exc_info[2],
|
|
self.traceback_limit, stderr
|
|
)
|
|
stderr.flush()
|
|
finally:
|
|
exc_info = None
|
|
|
|
def handle_error(self):
|
|
"""Log current error, and send error output to client if possible"""
|
|
self.log_exception(sys.exc_info())
|
|
if not self.headers_sent:
|
|
self.result = self.error_output(self.environ, self.start_response)
|
|
self.finish_response()
|
|
# XXX else: attempt advanced recovery techniques for HTML or text?
|
|
|
|
def error_output(self, environ, start_response):
|
|
"""WSGI mini-app to create error output
|
|
|
|
By default, this just uses the 'error_status', 'error_headers',
|
|
and 'error_body' attributes to generate an output page. It can
|
|
be overridden in a subclass to dynamically generate diagnostics,
|
|
choose an appropriate message for the user's preferred language, etc.
|
|
|
|
Note, however, that it's not recommended from a security perspective to
|
|
spit out diagnostics to any old user; ideally, you should have to do
|
|
something special to enable diagnostic output, which is why we don't
|
|
include any here!
|
|
"""
|
|
start_response(self.error_status,self.error_headers[:],sys.exc_info())
|
|
return [self.error_body]
|
|
|
|
|
|
# Pure abstract methods; *must* be overridden in subclasses
|
|
|
|
def _write(self,data):
|
|
"""Override in subclass to buffer data for send to client
|
|
|
|
It's okay if this method actually transmits the data; BaseHandler
|
|
just separates write and flush operations for greater efficiency
|
|
when the underlying system actually has such a distinction.
|
|
"""
|
|
raise NotImplementedError
|
|
|
|
def _flush(self):
|
|
"""Override in subclass to force sending of recent '_write()' calls
|
|
|
|
It's okay if this method is a no-op (i.e., if '_write()' actually
|
|
sends the data.
|
|
"""
|
|
raise NotImplementedError
|
|
|
|
def get_stdin(self):
|
|
"""Override in subclass to return suitable 'wsgi.input'"""
|
|
raise NotImplementedError
|
|
|
|
def get_stderr(self):
|
|
"""Override in subclass to return suitable 'wsgi.errors'"""
|
|
raise NotImplementedError
|
|
|
|
def add_cgi_vars(self):
|
|
"""Override in subclass to insert CGI variables in 'self.environ'"""
|
|
raise NotImplementedError
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class SimpleHandler(BaseHandler):
|
|
"""Handler that's just initialized with streams, environment, etc.
|
|
|
|
This handler subclass is intended for synchronous HTTP/1.0 origin servers,
|
|
and handles sending the entire response output, given the correct inputs.
|
|
|
|
Usage::
|
|
|
|
handler = SimpleHandler(
|
|
inp,out,err,env, multithread=False, multiprocess=True
|
|
)
|
|
handler.run(app)"""
|
|
|
|
def __init__(self,stdin,stdout,stderr,environ,
|
|
multithread=True, multiprocess=False
|
|
):
|
|
self.stdin = stdin
|
|
self.stdout = stdout
|
|
self.stderr = stderr
|
|
self.base_env = environ
|
|
self.wsgi_multithread = multithread
|
|
self.wsgi_multiprocess = multiprocess
|
|
|
|
def get_stdin(self):
|
|
return self.stdin
|
|
|
|
def get_stderr(self):
|
|
return self.stderr
|
|
|
|
def add_cgi_vars(self):
|
|
self.environ.update(self.base_env)
|
|
|
|
def _write(self,data):
|
|
self.stdout.write(data)
|
|
self._write = self.stdout.write
|
|
|
|
def _flush(self):
|
|
self.stdout.flush()
|
|
self._flush = self.stdout.flush
|
|
|
|
|
|
class BaseCGIHandler(SimpleHandler):
|
|
|
|
"""CGI-like systems using input/output/error streams and environ mapping
|
|
|
|
Usage::
|
|
|
|
handler = BaseCGIHandler(inp,out,err,env)
|
|
handler.run(app)
|
|
|
|
This handler class is useful for gateway protocols like ReadyExec and
|
|
FastCGI, that have usable input/output/error streams and an environment
|
|
mapping. It's also the base class for CGIHandler, which just uses
|
|
sys.stdin, os.environ, and so on.
|
|
|
|
The constructor also takes keyword arguments 'multithread' and
|
|
'multiprocess' (defaulting to 'True' and 'False' respectively) to control
|
|
the configuration sent to the application. It sets 'origin_server' to
|
|
False (to enable CGI-like output), and assumes that 'wsgi.run_once' is
|
|
False.
|
|
"""
|
|
|
|
origin_server = False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class CGIHandler(BaseCGIHandler):
|
|
|
|
"""CGI-based invocation via sys.stdin/stdout/stderr and os.environ
|
|
|
|
Usage::
|
|
|
|
CGIHandler().run(app)
|
|
|
|
The difference between this class and BaseCGIHandler is that it always
|
|
uses 'wsgi.run_once' of 'True', 'wsgi.multithread' of 'False', and
|
|
'wsgi.multiprocess' of 'True'. It does not take any initialization
|
|
parameters, but always uses 'sys.stdin', 'os.environ', and friends.
|
|
|
|
If you need to override any of these parameters, use BaseCGIHandler
|
|
instead.
|
|
"""
|
|
|
|
wsgi_run_once = True
|
|
|
|
def __init__(self):
|
|
BaseCGIHandler.__init__(
|
|
self, sys.stdin, sys.stdout, sys.stderr, dict(os.environ.items()),
|
|
multithread=False, multiprocess=True
|
|
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
#
|