2.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
2.2 +++ b/WebStack/Adapters/Helpers/wsgi_cgi.py Thu Mar 24 17:40:40 2005 +0000
2.3 @@ -0,0 +1,69 @@
2.4 +#!/usr/local/bin/python
2.5 +
2.6 +"""
2.7 +WSGI CGI handler code originating from PEP 333, transcribed by Titus Brown.
2.8 +Previously a standalone CGI program, this is now a module imported by the actual
2.9 +CGI programs.
2.10 +"""
2.11 +
2.12 +import os, sys
2.13 +
2.14 +def run_with_cgi(application):
2.15 +
2.16 + environ = dict(os.environ.items())
2.17 + environ['wsgi.input'] = sys.stdin
2.18 + environ['wsgi.errors'] = sys.stderr
2.19 + environ['wsgi.version'] = (1,0)
2.20 + environ['wsgi.multithread'] = False
2.21 + environ['wsgi.multiprocess'] = True
2.22 + environ['wsgi.run_once'] = True
2.23 +
2.24 + if environ.get('HTTPS','off') in ('on','1'):
2.25 + environ['wsgi.url_scheme'] = 'https'
2.26 + else:
2.27 + environ['wsgi.url_scheme'] = 'http'
2.28 +
2.29 + headers_set = []
2.30 + headers_sent = []
2.31 +
2.32 + def write(data):
2.33 + if not headers_set:
2.34 + raise AssertionError("write() before start_response()")
2.35 +
2.36 + elif not headers_sent:
2.37 + # Before the first output, send the stored headers
2.38 + status, response_headers = headers_sent[:] = headers_set
2.39 + sys.stdout.write('Status: %s\r\n' % status)
2.40 + for header in response_headers:
2.41 + sys.stdout.write('%s: %s\r\n' % header)
2.42 + sys.stdout.write('\r\n')
2.43 +
2.44 + sys.stdout.write(data)
2.45 + sys.stdout.flush()
2.46 +
2.47 + def start_response(status,response_headers,exc_info=None):
2.48 + if exc_info:
2.49 + try:
2.50 + if headers_sent:
2.51 + # Re-raise original exception if headers sent
2.52 + raise exc_info[0], exc_info[1], exc_info[2]
2.53 + finally:
2.54 + exc_info = None # avoid dangling circular ref
2.55 + elif headers_set:
2.56 + raise AssertionError("Headers already set!")
2.57 +
2.58 + headers_set[:] = [status,response_headers]
2.59 + return write
2.60 +
2.61 + result = application(environ, start_response)
2.62 + try:
2.63 + for data in result:
2.64 + if data: # don't send headers until body appears
2.65 + write(data)
2.66 + if not headers_sent:
2.67 + write('') # send headers now if body was empty
2.68 + finally:
2.69 + if hasattr(result,'close'):
2.70 + result.close()
2.71 +
2.72 +# vim: tabstop=4 expandtab shiftwidth=4