Back to index

python3.2  3.2.2
Public Member Functions | Public Attributes | Static Public Attributes
wsgiref.simple_server.ServerHandler Class Reference
Inheritance diagram for wsgiref.simple_server.ServerHandler:
Inheritance graph
[legend]
Collaboration diagram for wsgiref.simple_server.ServerHandler:
Collaboration graph
[legend]

List of all members.

Public Member Functions

def close
def get_stdin
def get_stderr
def add_cgi_vars
def run
def setup_environ
def finish_response
def get_scheme
def set_content_length
def cleanup_headers
def start_response
def send_preamble
def write
def sendfile
def finish_content
def send_headers
def result_is_file
def client_is_modern
def log_exception
def handle_error
def error_output

Public Attributes

 stdin
 stdout
 stderr
 base_env
 wsgi_multithread
 wsgi_multiprocess
 bytes_sent
 result
 environ

Static Public Attributes

 server_software = software_version
tuple wsgi_version = (1,0)
 wsgi_run_once = False
 origin_server = True
string http_version = "1.0"
tuple os_environ = read_environ()
 wsgi_file_wrapper = FileWrapper
 headers_class = Headers
 traceback_limit = None
string error_status = "500 Internal Server Error"
list error_headers = [('Content-Type','text/plain')]
string error_body = "A server error occurred. Please contact the administrator."
 status = resultNone
 headers_sent = False
 headers = None
int bytes_sent = 0

Detailed Description

Definition at line 27 of file simple_server.py.


Member Function Documentation

def wsgiref.handlers.SimpleHandler.add_cgi_vars (   self) [inherited]
Override in subclass to insert CGI variables in 'self.environ'

Reimplemented from wsgiref.handlers.BaseHandler.

Definition at line 447 of file handlers.py.

00447 
00448     def add_cgi_vars(self):
00449         self.environ.update(self.base_env)

Make any necessary header changes or defaults

Subclasses can extend this to add other defaults.

Definition at line 202 of file handlers.py.

00202 
00203     def cleanup_headers(self):
00204         """Make any necessary header changes or defaults
00205 
00206         Subclasses can extend this to add other defaults.
00207         """
00208         if 'Content-Length' not in self.headers:
00209             self.set_content_length()

Here is the call graph for this function:

Here is the caller graph for this function:

True if client can accept status and headers

Definition at line 340 of file handlers.py.

00340 
00341     def client_is_modern(self):
00342         """True if client can accept status and headers"""
00343         return self.environ['SERVER_PROTOCOL'].upper() != 'HTTP/0.9'
00344 

Here is the caller graph for this function:

Close the iterable (if needed) and reset all instance vars

Subclasses may want to also drop the client connection.

Reimplemented from wsgiref.handlers.BaseHandler.

Definition at line 31 of file simple_server.py.

00031 
00032     def close(self):
00033         try:
00034             self.request_handler.log_request(
00035                 self.status.split(' ',1)[0], self.bytes_sent
00036             )
00037         finally:
00038             SimpleHandler.close(self)
00039 
00040 

Here is the caller graph for this function:

def wsgiref.handlers.BaseHandler.error_output (   self,
  environ,
  start_response 
) [inherited]
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!

Definition at line 369 of file handlers.py.

00369 
00370     def error_output(self, environ, start_response):
00371         """WSGI mini-app to create error output
00372 
00373         By default, this just uses the 'error_status', 'error_headers',
00374         and 'error_body' attributes to generate an output page.  It can
00375         be overridden in a subclass to dynamically generate diagnostics,
00376         choose an appropriate message for the user's preferred language, etc.
00377 
00378         Note, however, that it's not recommended from a security perspective to
00379         spit out diagnostics to any old user; ideally, you should have to do
00380         something special to enable diagnostic output, which is why we don't
00381         include any here!
00382         """
00383         start_response(self.error_status,self.error_headers[:],sys.exc_info())
00384         return [self.error_body]
00385 

Here is the call graph for this function:

Here is the caller graph for this function:

def wsgiref.handlers.BaseHandler.finish_content (   self) [inherited]
Ensure headers and content have both been sent

Definition at line 302 of file handlers.py.

00302 
00303     def finish_content(self):
00304         """Ensure headers and content have both been sent"""
00305         if not self.headers_sent:
00306             # Only zero Content-Length if not set by the application (so
00307             # that HEAD requests can be satisfied properly, see #3839)
00308             self.headers.setdefault('Content-Length', "0")
00309             self.send_headers()
00310         else:
00311             pass # XXX check if content-length was too short?

Here is the call graph for this function:

Here is the caller graph for this function:

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.

Definition at line 169 of file handlers.py.

00169 
00170     def finish_response(self):
00171         """Send any iterable data, then close self and the iterable
00172 
00173         Subclasses intended for use in asynchronous servers will
00174         want to redefine this method, such that it sets up callbacks
00175         in the event loop to iterate over the data, and to call
00176         'self.close()' once the response is finished.
00177         """
00178         if not self.result_is_file() or not self.sendfile():
00179             for data in self.result:
00180                 self.write(data)
00181             self.finish_content()
00182         self.close()
00183 

Here is the caller graph for this function:

def wsgiref.handlers.BaseHandler.get_scheme (   self) [inherited]
Return the URL scheme being used

Definition at line 184 of file handlers.py.

00184 
00185     def get_scheme(self):
00186         """Return the URL scheme being used"""
00187         return guess_scheme(self.environ)
00188 

Here is the call graph for this function:

def wsgiref.handlers.SimpleHandler.get_stderr (   self) [inherited]
Override in subclass to return suitable 'wsgi.errors'

Reimplemented from wsgiref.handlers.BaseHandler.

Definition at line 444 of file handlers.py.

00444 
00445     def get_stderr(self):
00446         return self.stderr

def wsgiref.handlers.SimpleHandler.get_stdin (   self) [inherited]
Override in subclass to return suitable 'wsgi.input'

Reimplemented from wsgiref.handlers.BaseHandler.

Definition at line 441 of file handlers.py.

00441 
00442     def get_stdin(self):
00443         return self.stdin

def wsgiref.handlers.BaseHandler.handle_error (   self) [inherited]
Log current error, and send error output to client if possible

Reimplemented in test.test_wsgiref.TestHandler.

Definition at line 361 of file handlers.py.

00361 
00362     def handle_error(self):
00363         """Log current error, and send error output to client if possible"""
00364         self.log_exception(sys.exc_info())
00365         if not self.headers_sent:
00366             self.result = self.error_output(self.environ, self.start_response)
00367             self.finish_response()
00368         # XXX else: attempt advanced recovery techniques for HTML or text?

Here is the call graph for this function:

Here is the caller graph for this function:

def wsgiref.handlers.BaseHandler.log_exception (   self,
  exc_info 
) [inherited]
Log the 'exc_info' tuple in the server log

Subclasses may override to retarget the output or change its format.

Definition at line 345 of file handlers.py.

00345 
00346     def log_exception(self,exc_info):
00347         """Log the 'exc_info' tuple in the server log
00348 
00349         Subclasses may override to retarget the output or change its format.
00350         """
00351         try:
00352             from traceback import print_exception
00353             stderr = self.get_stderr()
00354             print_exception(
00355                 exc_info[0], exc_info[1], exc_info[2],
00356                 self.traceback_limit, stderr
00357             )
00358             stderr.flush()
00359         finally:
00360             exc_info = None

Here is the call graph for this function:

Here is the caller graph for this function:

def wsgiref.handlers.BaseHandler.result_is_file (   self) [inherited]
True if 'self.result' is an instance of 'self.wsgi_file_wrapper'

Definition at line 334 of file handlers.py.

00334 
00335     def result_is_file(self):
00336         """True if 'self.result' is an instance of 'self.wsgi_file_wrapper'"""
00337         wrapper = self.wsgi_file_wrapper
00338         return wrapper is not None and isinstance(self.result,wrapper)
00339 

Here is the caller graph for this function:

def wsgiref.handlers.BaseHandler.run (   self,
  application 
) [inherited]
Invoke the application

Definition at line 128 of file handlers.py.

00128 
00129     def run(self, application):
00130         """Invoke the application"""
00131         # Note to self: don't move the close()!  Asynchronous servers shouldn't
00132         # call close() from finish_response(), so if you close() anywhere but
00133         # the double-error branch here, you'll break asynchronous servers by
00134         # prematurely closing.  Async servers must return from 'run()' without
00135         # closing if there might still be output to iterate over.
00136         try:
00137             self.setup_environ()
00138             self.result = application(self.environ, self.start_response)
00139             self.finish_response()
00140         except:
00141             try:
00142                 self.handle_error()
00143             except:
00144                 # If we get an error handling an error, just give up already!
00145                 self.close()
00146                 raise   # ...and let the actual server figure it out.
00147 

Here is the call graph for this function:

Here is the caller graph for this function:

def wsgiref.handlers.BaseHandler.send_headers (   self) [inherited]
Transmit headers to the client, via self._write()

Definition at line 325 of file handlers.py.

00325 
00326     def send_headers(self):
00327         """Transmit headers to the client, via self._write()"""
00328         self.cleanup_headers()
00329         self.headers_sent = True
00330         if not self.origin_server or self.client_is_modern():
00331             self.send_preamble()
00332             self._write(bytes(self.headers))
00333 

Here is the call graph for this function:

Here is the caller graph for this function:

def wsgiref.handlers.BaseHandler.send_preamble (   self) [inherited]
Transmit version/status/date/server, via self._write()

Definition at line 246 of file handlers.py.

00246 
00247     def send_preamble(self):
00248         """Transmit version/status/date/server, via self._write()"""
00249         if self.origin_server:
00250             if self.client_is_modern():
00251                 self._write(('HTTP/%s %s\r\n' % (self.http_version,self.status)).encode('iso-8859-1'))
00252                 if 'Date' not in self.headers:
00253                     self._write(
00254                         ('Date: %s\r\n' % format_date_time(time.time())).encode('iso-8859-1')
00255                     )
00256                 if self.server_software and 'Server' not in self.headers:
00257                     self._write(('Server: %s\r\n' % self.server_software).encode('iso-8859-1'))
00258         else:
00259             self._write(('Status: %s\r\n' % self.status).encode('iso-8859-1'))

Here is the call graph for this function:

Here is the caller graph for this function:

def wsgiref.handlers.BaseHandler.sendfile (   self) [inherited]
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.

Definition at line 281 of file handlers.py.

00281 
00282     def sendfile(self):
00283         """Platform-specific file transmission
00284 
00285         Override this method in subclasses to support platform-specific
00286         file transmission.  It is only called if the application's
00287         return iterable ('self.result') is an instance of
00288         'self.wsgi_file_wrapper'.
00289 
00290         This method should return a true value if it was able to actually
00291         transmit the wrapped file-like object using a platform-specific
00292         approach.  It should return a false value if normal iteration
00293         should be used instead.  An exception can be raised to indicate
00294         that transmission was attempted, but failed.
00295 
00296         NOTE: this method should call 'self.send_headers()' if
00297         'self.headers_sent' is false and it is going to attempt direct
00298         transmission of the file.
00299         """
00300         return False   # No platform-specific transmission by default
00301 

Here is the caller graph for this function:

Compute Content-Length or switch to chunked encoding if possible

Definition at line 189 of file handlers.py.

00189 
00190     def set_content_length(self):
00191         """Compute Content-Length or switch to chunked encoding if possible"""
00192         try:
00193             blocks = len(self.result)
00194         except (TypeError,AttributeError,NotImplementedError):
00195             pass
00196         else:
00197             if blocks==1:
00198                 self.headers['Content-Length'] = str(self.bytes_sent)
00199                 return
00200         # XXX Try for chunked encoding if origin server and client is 1.1
00201 

Here is the caller graph for this function:

def wsgiref.handlers.BaseHandler.setup_environ (   self) [inherited]
Set up the environment for one request

Definition at line 148 of file handlers.py.

00148 
00149     def setup_environ(self):
00150         """Set up the environment for one request"""
00151 
00152         env = self.environ = self.os_environ.copy()
00153         self.add_cgi_vars()
00154 
00155         env['wsgi.input']        = self.get_stdin()
00156         env['wsgi.errors']       = self.get_stderr()
00157         env['wsgi.version']      = self.wsgi_version
00158         env['wsgi.run_once']     = self.wsgi_run_once
00159         env['wsgi.url_scheme']   = self.get_scheme()
00160         env['wsgi.multithread']  = self.wsgi_multithread
00161         env['wsgi.multiprocess'] = self.wsgi_multiprocess
00162 
00163         if self.wsgi_file_wrapper is not None:
00164             env['wsgi.file_wrapper'] = self.wsgi_file_wrapper
00165 
00166         if self.origin_server and self.server_software:
00167             env.setdefault('SERVER_SOFTWARE',self.server_software)
00168 

Here is the caller graph for this function:

def wsgiref.handlers.BaseHandler.start_response (   self,
  status,
  headers,
  exc_info = None 
) [inherited]
'start_response()' callable as specified by PEP 3333

Definition at line 210 of file handlers.py.

00210 
00211     def start_response(self, status, headers,exc_info=None):
00212         """'start_response()' callable as specified by PEP 3333"""
00213 
00214         if exc_info:
00215             try:
00216                 if self.headers_sent:
00217                     # Re-raise original exception if headers sent
00218                     raise exc_info[0](exc_info[1]).with_traceback(exc_info[2])
00219             finally:
00220                 exc_info = None        # avoid dangling circular ref
00221         elif self.headers is not None:
00222             raise AssertionError("Headers already set!")
00223 
00224         self.status = status
00225         self.headers = self.headers_class(headers)
00226         status = self._convert_string_type(status, "Status")
00227         assert len(status)>=4,"Status must be at least 4 characters"
00228         assert int(status[:3]),"Status message must begin w/3-digit code"
00229         assert status[3]==" ", "Status message must have a space after code"
00230 
00231         if __debug__:
00232             for name, val in headers:
00233                 name = self._convert_string_type(name, "Header name")
00234                 val = self._convert_string_type(val, "Header value")
00235                 assert not is_hop_by_hop(name),"Hop-by-hop headers not allowed"
00236 
00237         return self.write

Here is the caller graph for this function:

def wsgiref.handlers.BaseHandler.write (   self,
  data 
) [inherited]
'write()' callable as specified by PEP 3333

Definition at line 260 of file handlers.py.

00260 
00261     def write(self, data):
00262         """'write()' callable as specified by PEP 3333"""
00263 
00264         assert type(data) is bytes, \
00265             "write() argument must be a bytes instance"
00266 
00267         if not self.status:
00268             raise AssertionError("write() before start_response()")
00269 
00270         elif not self.headers_sent:
00271             # Before the first output, send the stored headers
00272             self.bytes_sent = len(data)    # make sure we know content-length
00273             self.send_headers()
00274         else:
00275             self.bytes_sent += len(data)
00276 
00277         # XXX check Content-Length and truncate if too many bytes written?
00278         self._write(data)
00279         self._flush()
00280 


Member Data Documentation

Definition at line 437 of file handlers.py.

Definition at line 126 of file handlers.py.

Definition at line 271 of file handlers.py.

Definition at line 151 of file handlers.py.

string wsgiref.handlers.BaseHandler.error_body = "A server error occurred. Please contact the administrator." [static, inherited]

Definition at line 120 of file handlers.py.

list wsgiref.handlers.BaseHandler.error_headers = [('Content-Type','text/plain')] [static, inherited]

Definition at line 119 of file handlers.py.

string wsgiref.handlers.BaseHandler.error_status = "500 Internal Server Error" [static, inherited]

Definition at line 118 of file handlers.py.

wsgiref.handlers.BaseHandler.headers = None [static, inherited]

Definition at line 125 of file handlers.py.

wsgiref.handlers.BaseHandler.headers_class = Headers [static, inherited]

Definition at line 114 of file handlers.py.

wsgiref.handlers.BaseHandler.headers_sent = False [static, inherited]

Definition at line 124 of file handlers.py.

Definition at line 104 of file handlers.py.

wsgiref.handlers.BaseHandler.origin_server = True [static, inherited]

Reimplemented in wsgiref.handlers.BaseCGIHandler.

Definition at line 103 of file handlers.py.

tuple wsgiref.handlers.BaseHandler.os_environ = read_environ() [static, inherited]

Definition at line 137 of file handlers.py.

Reimplemented from wsgiref.handlers.BaseHandler.

Definition at line 29 of file simple_server.py.

wsgiref.handlers.BaseHandler.status = resultNone [static, inherited]

Definition at line 123 of file handlers.py.

Definition at line 436 of file handlers.py.

Definition at line 434 of file handlers.py.

Definition at line 435 of file handlers.py.

Definition at line 117 of file handlers.py.

wsgiref.handlers.BaseHandler.wsgi_file_wrapper = FileWrapper [static, inherited]

Definition at line 113 of file handlers.py.

Reimplemented from wsgiref.handlers.BaseHandler.

Definition at line 439 of file handlers.py.

Reimplemented from wsgiref.handlers.BaseHandler.

Definition at line 438 of file handlers.py.

wsgiref.handlers.BaseHandler.wsgi_run_once = False [static, inherited]

Reimplemented in wsgiref.handlers.IISCGIHandler, and wsgiref.handlers.CGIHandler.

Definition at line 101 of file handlers.py.

tuple wsgiref.handlers.BaseHandler.wsgi_version = (1,0) [static, inherited]

Definition at line 98 of file handlers.py.


The documentation for this class was generated from the following file: