annotate CSP2/CSP2_env/env-d9b9114564458d9d-741b3de822f2aaca6c6caa4325c4afce/lib/python3.8/wsgiref/handlers.py @ 69:33d812a61356

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