| 1 | # (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org) |
|---|
| 2 | # Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php |
|---|
| 3 | import os |
|---|
| 4 | import sys |
|---|
| 5 | |
|---|
| 6 | ## FIXME: this should be deprecated in favor of wsgiref |
|---|
| 7 | |
|---|
| 8 | def paste_run_cgi(wsgi_app, global_conf): |
|---|
| 9 | run_with_cgi(wsgi_app) |
|---|
| 10 | |
|---|
| 11 | stdout = sys.__stdout__ |
|---|
| 12 | |
|---|
| 13 | # Taken from the WSGI spec: |
|---|
| 14 | |
|---|
| 15 | def run_with_cgi(application): |
|---|
| 16 | |
|---|
| 17 | environ = dict(os.environ.items()) |
|---|
| 18 | environ['wsgi.input'] = sys.stdin |
|---|
| 19 | environ['wsgi.errors'] = sys.stderr |
|---|
| 20 | environ['wsgi.version'] = (1,0) |
|---|
| 21 | environ['wsgi.multithread'] = False |
|---|
| 22 | environ['wsgi.multiprocess'] = True |
|---|
| 23 | environ['wsgi.run_once'] = True |
|---|
| 24 | |
|---|
| 25 | if environ.get('HTTPS','off') in ('on','1'): |
|---|
| 26 | environ['wsgi.url_scheme'] = 'https' |
|---|
| 27 | else: |
|---|
| 28 | environ['wsgi.url_scheme'] = 'http' |
|---|
| 29 | |
|---|
| 30 | headers_set = [] |
|---|
| 31 | headers_sent = [] |
|---|
| 32 | |
|---|
| 33 | def write(data): |
|---|
| 34 | if not headers_set: |
|---|
| 35 | raise AssertionError("write() before start_response()") |
|---|
| 36 | |
|---|
| 37 | elif not headers_sent: |
|---|
| 38 | # Before the first output, send the stored headers |
|---|
| 39 | status, response_headers = headers_sent[:] = headers_set |
|---|
| 40 | stdout.write('Status: %s\r\n' % status) |
|---|
| 41 | for header in response_headers: |
|---|
| 42 | stdout.write('%s: %s\r\n' % header) |
|---|
| 43 | stdout.write('\r\n') |
|---|
| 44 | |
|---|
| 45 | stdout.write(data) |
|---|
| 46 | stdout.flush() |
|---|
| 47 | |
|---|
| 48 | def start_response(status,response_headers,exc_info=None): |
|---|
| 49 | if exc_info: |
|---|
| 50 | try: |
|---|
| 51 | if headers_sent: |
|---|
| 52 | # Re-raise original exception if headers sent |
|---|
| 53 | raise exc_info[0], exc_info[1], exc_info[2] |
|---|
| 54 | finally: |
|---|
| 55 | exc_info = None # avoid dangling circular ref |
|---|
| 56 | elif headers_set: |
|---|
| 57 | raise AssertionError("Headers already set!") |
|---|
| 58 | |
|---|
| 59 | headers_set[:] = [status,response_headers] |
|---|
| 60 | return write |
|---|
| 61 | |
|---|
| 62 | result = application(environ, start_response) |
|---|
| 63 | try: |
|---|
| 64 | for data in result: |
|---|
| 65 | if data: # don't send headers until body appears |
|---|
| 66 | write(data) |
|---|
| 67 | if not headers_sent: |
|---|
| 68 | write('') # send headers now if body was empty |
|---|
| 69 | finally: |
|---|
| 70 | if hasattr(result,'close'): |
|---|
| 71 | result.close() |
|---|