paulb@302 | 1 | #!/usr/bin/env python |
paulb@302 | 2 | |
paulb@302 | 3 | """ |
paulb@302 | 4 | WSGI adapter. |
paulb@302 | 5 | """ |
paulb@302 | 6 | |
paulb@302 | 7 | import WebStack.WSGI |
paulb@302 | 8 | from WebStack.Generic import EndOfResponse |
paulb@302 | 9 | |
paulb@302 | 10 | class WSGIAdapter: |
paulb@302 | 11 | |
paulb@302 | 12 | "A WSGI adapter class." |
paulb@302 | 13 | |
paulb@302 | 14 | def __init__(self, resource, authenticator=None): |
paulb@302 | 15 | |
paulb@302 | 16 | """ |
paulb@302 | 17 | Initialise the adapter with the given WebStack 'resource' and the |
paulb@302 | 18 | optional 'authenticator'. |
paulb@302 | 19 | """ |
paulb@302 | 20 | |
paulb@302 | 21 | self.resource = resource |
paulb@302 | 22 | self.authenticator = authenticator |
paulb@302 | 23 | |
paulb@302 | 24 | def __call__(self, environ, start_response): |
paulb@302 | 25 | |
paulb@302 | 26 | """ |
paulb@302 | 27 | Dispatch to the root application-specific 'resource'. Return a list of |
paulb@302 | 28 | strings comprising the response body text. |
paulb@302 | 29 | """ |
paulb@302 | 30 | |
paulb@305 | 31 | # NOTE: It would be best to give start_response to the transaction so |
paulb@305 | 32 | # NOTE: that the underlying response's write method can be used by the |
paulb@305 | 33 | # NOTE: transaction directly. Unfortunately, WebStack doesn't provide |
paulb@305 | 34 | # NOTE: any means of declaring when the headers have been set and when |
paulb@305 | 35 | # NOTE: response body output is the only thing to be subsequently |
paulb@305 | 36 | # NOTE: produced. |
paulb@305 | 37 | |
paulb@302 | 38 | trans = WebStack.WSGI.Transaction(environ) |
paulb@302 | 39 | |
paulb@302 | 40 | try: |
paulb@302 | 41 | if self.authenticator is None or self.authenticator.authenticate(trans): |
paulb@302 | 42 | try: |
paulb@302 | 43 | self.resource.respond(trans) |
paulb@302 | 44 | except EndOfResponse: |
paulb@302 | 45 | pass |
paulb@302 | 46 | else: |
paulb@302 | 47 | trans.set_response_code(401) # Unauthorized |
paulb@302 | 48 | trans.set_header_value("WWW-Authenticate", '%s realm="%s"' % ( |
paulb@302 | 49 | self.authenticator.get_auth_type(), self.authenticator.get_realm())) |
paulb@302 | 50 | finally: |
paulb@302 | 51 | trans.commit() |
paulb@302 | 52 | |
paulb@302 | 53 | # NOTE: Provide sensible messages. |
paulb@305 | 54 | # NOTE: Ignoring the write method returned by start_response. |
paulb@302 | 55 | |
paulb@302 | 56 | start_response( |
paulb@302 | 57 | "%s WebStack status" % trans.get_response_code(), |
paulb@302 | 58 | trans.get_wsgi_headers() |
paulb@302 | 59 | ) |
paulb@302 | 60 | return [trans.get_wsgi_content()] |
paulb@302 | 61 | |
paulb@302 | 62 | # vim: tabstop=4 expandtab shiftwidth=4 |