1 #!/usr/bin/env python 2 3 """ 4 Twisted adapter. 5 """ 6 7 import WebStack.Twisted 8 from WebStack.Generic import EndOfResponse 9 import twisted.web.resource 10 11 class Dispatcher(twisted.web.resource.Resource): 12 13 "A class dispatching requests to WebStack resources." 14 15 isLeaf = 1 16 17 def __init__(self, resource, authenticator=None, handle_errors=1): 18 19 """ 20 Initialise the root application-specific 'resource' and optional 21 'authenticator'. The optional 'handle_errors' parameter (if true) causes 22 handlers to deal with uncaught exceptions cleanly. 23 """ 24 25 twisted.web.resource.Resource.__init__(self) 26 self.webstack_resource = resource 27 self.webstack_authenticator = authenticator 28 self.handle_errors = handle_errors 29 30 def getChild(self, path, request): 31 raise NotImplementedError, "getChild" 32 33 def render(self, request): 34 35 "Dispatch the given 'request' to the root application-specific resource." 36 37 trans = WebStack.Twisted.Transaction(request) 38 if self.webstack_authenticator is None or self.webstack_authenticator.authenticate(trans): 39 try: 40 self.webstack_resource.respond(trans) 41 except EndOfResponse: 42 pass 43 except: 44 if self.handle_errors: 45 trans.set_response_code(500) # Internal error 46 else: 47 raise 48 else: 49 trans.set_response_code(401) # Unauthorized 50 trans.set_header_value("WWW-Authenticate", '%s realm="%s"' % ( 51 self.webstack_authenticator.get_auth_type(), self.webstack_authenticator.get_realm())) 52 53 trans.commit() 54 request.finish() 55 return twisted.web.server.NOT_DONE_YET 56 57 # vim: tabstop=4 expandtab shiftwidth=4