11 import os, sys |
11 import os, sys |
12 |
12 |
13 def launch(application): |
13 def launch(application): |
14 |
14 |
15 environ = dict(os.environ.items()) |
15 environ = dict(os.environ.items()) |
16 environ['wsgi.input'] = sys.stdin |
16 environ['wsgi.input'] = sys.stdin |
17 environ['wsgi.errors'] = sys.stderr |
17 environ['wsgi.errors'] = sys.stderr |
18 environ['wsgi.version'] = (1,0) |
18 environ['wsgi.version'] = (1, 0) |
19 environ['wsgi.multithread'] = False |
19 environ['wsgi.multithread'] = False |
20 environ['wsgi.multiprocess'] = True |
20 environ['wsgi.multiprocess'] = True |
21 environ['wsgi.run_once'] = True |
21 environ['wsgi.run_once'] = True |
22 |
22 |
23 if environ.get('HTTPS','off') in ('on','1'): |
23 if environ.get('HTTPS','off') in ('on','1'): |
24 environ['wsgi.url_scheme'] = 'https' |
24 environ['wsgi.url_scheme'] = 'https' |
25 else: |
25 else: |
26 environ['wsgi.url_scheme'] = 'http' |
26 environ['wsgi.url_scheme'] = 'http' |
29 headers_sent = [] |
29 headers_sent = [] |
30 out = sys.stdout |
30 out = sys.stdout |
31 |
31 |
32 def write(data): |
32 def write(data): |
33 if not headers_set: |
33 if not headers_set: |
34 raise AssertionError("write() before start_response()") |
34 raise AssertionError("write() before start_response()") |
35 |
35 |
36 elif not headers_sent: |
36 elif not headers_sent: |
37 # Before the first output, send the stored headers |
37 # Before the first output, send the stored headers |
38 status, response_headers = headers_sent[:] = headers_set |
38 status, response_headers = headers_sent[:] = headers_set |
39 out.write('Status: %s\r\n' % status) |
39 out.write('Status: %s\r\n' % status) |
40 for header in response_headers: |
40 for header in response_headers: |
41 out.write('%s: %s\r\n' % header) |
41 out.write('%s: %s\r\n' % header) |
42 out.write('\r\n') |
42 out.write('\r\n') |
43 |
43 |
44 out.write(data) |
44 out.write(data) |
45 out.flush() |
45 out.flush() |
46 |
46 |
47 def start_response(status,response_headers,exc_info=None): |
47 def start_response(status, response_headers, exc_info=None): |
48 if exc_info: |
48 if exc_info: |
49 try: |
49 try: |
50 if headers_sent: |
50 if headers_sent: |
51 # Re-raise original exception if headers sent |
51 # Re-raise original exception if headers sent |
52 raise exc_info[0], exc_info[1], exc_info[2] |
52 raise exc_info[0], exc_info[1], exc_info[2] |
53 finally: |
53 finally: |
54 exc_info = None # avoid dangling circular ref |
54 exc_info = None # avoid dangling circular ref |
55 elif headers_set: |
55 elif headers_set: |
56 raise AssertionError("Headers already set!") |
56 raise AssertionError("Headers already set!") |
57 |
57 |
58 headers_set[:] = [status,response_headers] |
58 headers_set[:] = [status, response_headers] |
59 return write |
59 return write |
60 |
60 |
61 result = application(environ, start_response) |
61 result = application(environ, start_response) |
62 try: |
62 try: |
63 for data in result: |
63 for data in result: |