1 #!/usr/bin/env python 2 3 "Mapping from names to resources." 4 5 import WebStack.Generic 6 7 class MapResource: 8 9 "A resource mapping names to other resources." 10 11 def __init__(self, mapping): 12 13 """ 14 Initialise the resource with a 'mapping' of names to resources. The 15 'mapping' should be a dictionary-like object employing simple names 16 without "/" characters; the special value None is used where no name 17 is found in the request path. 18 """ 19 20 self.mapping = mapping 21 22 def respond(self, trans): 23 24 """ 25 Using the path information from the given transaction 'trans', invoke 26 mapped resources. Otherwise return an error condition. 27 """ 28 29 # Get the path info. 30 31 parts = trans.get_path_info().split("/") 32 33 # The first part should always be empty. 34 35 if len(parts) > 1: 36 name = parts[1] 37 else: 38 name = None 39 print "*", name 40 41 # Get the mapped resource. 42 43 resource = self.mapping.get(name) 44 print "**", resource 45 46 # If a resource was found, change the transaction's path info, then 47 # invoke the transaction, transferring control completely. 48 49 new_path_info = "/".join(parts[0:1] + parts[2:]) 50 print "***", new_path_info 51 trans.set_path_info(new_path_info) 52 53 if resource is not None: 54 resource.respond(trans) 55 return 56 57 # Otherwise, signal an error. 58 59 self.send_error(trans) 60 61 def send_error(self, trans): 62 63 "Send the error using the given 'trans'." 64 65 trans.set_response_code(404) 66 trans.set_content_type(WebStack.Generic.ContentType("text/plain")) 67 out = trans.get_response_stream() 68 out.write("Resource '%s' not found." % trans.get_path_info()) 69 70 # vim: tabstop=4 expandtab shiftwidth=4