wsgicgi.py
73 lines
| 2.3 KiB
| text/x-python
|
PythonLexer
|
r2506 | # hgweb/wsgicgi.py - CGI->WSGI translator | ||
# | ||||
# Copyright 2006 Eric Hopper <hopper@omnifarious.org> | ||||
# | ||||
# This software may be used and distributed according to the terms | ||||
# of the GNU General Public License, incorporated herein by reference. | ||||
# | ||||
# This was originally copied from the public domain code at | ||||
# http://www.python.org/dev/peps/pep-0333/#the-server-gateway-side | ||||
import os, sys | ||||
|
r4076 | from mercurial import util | ||
|
r2506 | |||
def launch(application): | ||||
|
r4484 | util.set_binary(sys.stdin) | ||
|
r4076 | util.set_binary(sys.stdout) | ||
|
r2506 | |||
environ = dict(os.environ.items()) | ||||
|
r3673 | environ['wsgi.input'] = sys.stdin | ||
environ['wsgi.errors'] = sys.stderr | ||||
environ['wsgi.version'] = (1, 0) | ||||
environ['wsgi.multithread'] = False | ||||
|
r2506 | environ['wsgi.multiprocess'] = True | ||
|
r3673 | environ['wsgi.run_once'] = True | ||
|
r2506 | |||
|
r4869 | if environ.get('HTTPS','off').lower() in ('on','1','yes'): | ||
|
r2506 | environ['wsgi.url_scheme'] = 'https' | ||
else: | ||||
environ['wsgi.url_scheme'] = 'http' | ||||
headers_set = [] | ||||
headers_sent = [] | ||||
|
r2558 | out = sys.stdout | ||
|
r2506 | |||
def write(data): | ||||
if not headers_set: | ||||
|
r3673 | raise AssertionError("write() before start_response()") | ||
|
r2506 | |||
elif not headers_sent: | ||||
|
r3673 | # Before the first output, send the stored headers | ||
status, response_headers = headers_sent[:] = headers_set | ||||
out.write('Status: %s\r\n' % status) | ||||
for header in response_headers: | ||||
out.write('%s: %s\r\n' % header) | ||||
out.write('\r\n') | ||||
|
r2506 | |||
|
r2558 | out.write(data) | ||
out.flush() | ||||
|
r2506 | |||
|
r3673 | def start_response(status, response_headers, exc_info=None): | ||
|
r2506 | if exc_info: | ||
try: | ||||
if 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 headers_set: | ||||
raise AssertionError("Headers already set!") | ||||
|
r3673 | headers_set[:] = [status, response_headers] | ||
|
r2506 | return write | ||
result = application(environ, start_response) | ||||
try: | ||||
for data in result: | ||||
if data: # don't send headers until body appears | ||||
write(data) | ||||
if not headers_sent: | ||||
write('') # send headers now if body was empty | ||||
finally: | ||||
if hasattr(result,'close'): | ||||
result.close() | ||||