paulb@109 | 1 | #!/usr/bin/env python |
paulb@109 | 2 | |
paulb@109 | 3 | """ |
paulb@109 | 4 | CGI adapter. |
paulb@109 | 5 | """ |
paulb@109 | 6 | |
paulb@109 | 7 | import WebStack.CGI |
paulb@297 | 8 | from WebStack.Generic import EndOfResponse |
paulb@109 | 9 | import sys, os |
paulb@109 | 10 | |
paulb@321 | 11 | def deploy(resource, authenticator=None, input=None, output=None, env=None, handle_errors=1): |
paulb@109 | 12 | |
paulb@109 | 13 | """ |
paulb@109 | 14 | Dispatch to the root application-specific 'resource'. Employ the optional |
paulb@134 | 15 | 'authenticator' to control access to the resource. If the optional 'input' |
paulb@134 | 16 | stream, 'output' stream or environment 'env' are specified, use them instead |
paulb@134 | 17 | of the defaults: standard input, standard output and the operating system |
paulb@134 | 18 | environment respectively. Note that 'env' must evaluate to true for it to |
paulb@310 | 19 | replace the default. The optional 'handle_errors' parameter (if true) causes |
paulb@310 | 20 | handlers to deal with uncaught exceptions cleanly. |
paulb@109 | 21 | """ |
paulb@109 | 22 | |
paulb@134 | 23 | trans = WebStack.CGI.Transaction(input or sys.stdin, output or sys.stdout, |
paulb@134 | 24 | env or os.environ) |
paulb@109 | 25 | |
paulb@109 | 26 | try: |
paulb@109 | 27 | if authenticator is None or authenticator.authenticate(trans): |
paulb@297 | 28 | try: |
paulb@297 | 29 | resource.respond(trans) |
paulb@297 | 30 | except EndOfResponse: |
paulb@297 | 31 | pass |
paulb@310 | 32 | except: |
paulb@337 | 33 | if handle_errors: |
paulb@310 | 34 | trans.set_response_code(500) # Internal error |
paulb@310 | 35 | else: |
paulb@310 | 36 | raise |
paulb@109 | 37 | else: |
paulb@109 | 38 | trans.set_response_code(401) # Unauthorized |
paulb@109 | 39 | trans.set_header_value("WWW-Authenticate", '%s realm="%s"' % ( |
paulb@109 | 40 | authenticator.get_auth_type(), authenticator.get_realm())) |
paulb@109 | 41 | finally: |
paulb@109 | 42 | trans.commit() |
paulb@109 | 43 | |
paulb@109 | 44 | # vim: tabstop=4 expandtab shiftwidth=4 |