Ticket #2407: cgi.py

File cgi.py, 2.2 KB (added by Marc Fargas <telenieko@…>, 18 years ago)

to be placed in django/core/servers

Line 
1"""
2CGI wrapper for Django using the WSGI protocol
3
4Code copy/pasted from PEP-0333 and then tweaked to serve django.
5http://www.python.org/dev/peps/pep-0333/#the-server-gateway-side
6"""
7
8import os, sys
9import django.core.handlers.wsgi
10
11def runcgi():
12 environ = dict(os.environ.items())
13 environ['wsgi.input'] = sys.stdin
14 environ['wsgi.errors'] = sys.stderr
15 environ['wsgi.version'] = (1,0)
16 environ['wsgi.multithread'] = False
17 environ['wsgi.multiprocess'] = True
18 environ['wsgi.run_once'] = True
19
20 application = django.core.handlers.wsgi.WSGIHandler()
21
22 if environ.get('HTTPS','off') in ('on','1'):
23 environ['wsgi.url_scheme'] = 'https'
24 else:
25 environ['wsgi.url_scheme'] = 'http'
26
27 headers_set = []
28 headers_sent = []
29
30 def write(data):
31 if not headers_set:
32 raise AssertionError("write() before start_response()")
33
34 elif not headers_sent:
35 # Before the first output, send the stored headers
36 status, response_headers = headers_sent[:] = headers_set
37 sys.stdout.write('Status: %s\r\n' % status)
38 for header in response_headers:
39 sys.stdout.write('%s: %s\r\n' % header)
40 sys.stdout.write('\r\n')
41
42 sys.stdout.write(data)
43 sys.stdout.flush()
44
45 def start_response(status,response_headers,exc_info=None):
46 if exc_info:
47 try:
48 if headers_sent:
49 # Re-raise original exception if headers sent
50 raise exc_info[0], exc_info[1], exc_info[2]
51 finally:
52 exc_info = None # avoid dangling circular ref
53 elif headers_set:
54 raise AssertionError("Headers already set!")
55
56 headers_set[:] = [status,response_headers]
57 return write
58
59 result = application(environ, start_response)
60 try:
61 for data in result:
62 if data: # don't send headers until body appears
63 write(data)
64 if not headers_sent:
65 write('') # send headers now if body was empty
66 finally:
67 if hasattr(result,'close'):
68 result.close()
Back to Top