cgi.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. # Taken from <http://www.python.org/dev/peps/pep-0333/>
  2. # which was placed in the public domain.
  3. import os, sys
  4. __all__ = ['WSGIServer']
  5. class WSGIServer(object):
  6. def __init__(self, application):
  7. self.application = application
  8. def run(self):
  9. environ = dict(os.environ.items())
  10. environ['wsgi.input'] = sys.stdin
  11. environ['wsgi.errors'] = sys.stderr
  12. environ['wsgi.version'] = (1,0)
  13. environ['wsgi.multithread'] = False
  14. environ['wsgi.multiprocess'] = True
  15. environ['wsgi.run_once'] = True
  16. if environ.get('HTTPS','off') in ('on','1'):
  17. environ['wsgi.url_scheme'] = 'https'
  18. else:
  19. environ['wsgi.url_scheme'] = 'http'
  20. headers_set = []
  21. headers_sent = []
  22. def write(data):
  23. if not headers_set:
  24. raise AssertionError("write() before start_response()")
  25. elif not headers_sent:
  26. # Before the first output, send the stored headers
  27. status, response_headers = headers_sent[:] = headers_set
  28. sys.stdout.write('Status: %s\r\n' % status)
  29. for header in response_headers:
  30. sys.stdout.write('%s: %s\r\n' % header)
  31. sys.stdout.write('\r\n')
  32. sys.stdout.write(data)
  33. sys.stdout.flush()
  34. def start_response(status,response_headers,exc_info=None):
  35. if exc_info:
  36. try:
  37. if headers_sent:
  38. # Re-raise original exception if headers sent
  39. raise exc_info[0], exc_info[1], exc_info[2]
  40. finally:
  41. exc_info = None # avoid dangling circular ref
  42. elif headers_set:
  43. raise AssertionError("Headers already set!")
  44. headers_set[:] = [status,response_headers]
  45. return write
  46. result = self.application(environ, start_response)
  47. try:
  48. for data in result:
  49. if data: # don't send headers until body appears
  50. write(data)
  51. if not headers_sent:
  52. write('') # send headers now if body was empty
  53. finally:
  54. if hasattr(result,'close'):
  55. result.close()