Back to index

moin  1.9.0~rc2
cgi.py
Go to the documentation of this file.
00001 # Taken from <http://www.python.org/dev/peps/pep-0333/>
00002 # which was placed in the public domain.
00003 
00004 import os, sys
00005 
00006 
00007 __all__ = ['WSGIServer']
00008 
00009 
00010 class WSGIServer(object):
00011 
00012     def __init__(self, application):
00013         self.application = application
00014 
00015     def run(self):
00016 
00017         environ = dict(os.environ.items())
00018         environ['wsgi.input']        = sys.stdin
00019         environ['wsgi.errors']       = sys.stderr
00020         environ['wsgi.version']      = (1,0)
00021         environ['wsgi.multithread']  = False
00022         environ['wsgi.multiprocess'] = True
00023         environ['wsgi.run_once']     = True
00024 
00025         if environ.get('HTTPS','off') in ('on','1'):
00026             environ['wsgi.url_scheme'] = 'https'
00027         else:
00028             environ['wsgi.url_scheme'] = 'http'
00029 
00030         headers_set = []
00031         headers_sent = []
00032 
00033         def write(data):
00034             if not headers_set:
00035                  raise AssertionError("write() before start_response()")
00036 
00037             elif not headers_sent:
00038                  # Before the first output, send the stored headers
00039                  status, response_headers = headers_sent[:] = headers_set
00040                  sys.stdout.write('Status: %s\r\n' % status)
00041                  for header in response_headers:
00042                      sys.stdout.write('%s: %s\r\n' % header)
00043                  sys.stdout.write('\r\n')
00044 
00045             sys.stdout.write(data)
00046             sys.stdout.flush()
00047 
00048         def start_response(status,response_headers,exc_info=None):
00049             if exc_info:
00050                 try:
00051                     if headers_sent:
00052                         # Re-raise original exception if headers sent
00053                         raise exc_info[0], exc_info[1], exc_info[2]
00054                 finally:
00055                     exc_info = None     # avoid dangling circular ref
00056             elif headers_set:
00057                 raise AssertionError("Headers already set!")
00058 
00059             headers_set[:] = [status,response_headers]
00060             return write
00061 
00062         result = self.application(environ, start_response)
00063         try:
00064             for data in result:
00065                 if data:    # don't send headers until body appears
00066                     write(data)
00067             if not headers_sent:
00068                 write('')   # send headers now if body was empty
00069         finally:
00070             if hasattr(result,'close'):
00071                 result.close()