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 40 # Get the mapped resource. 41 42 resource = self.mapping.get(name) 43 44 # If a resource was found, change the transaction's path info, then 45 # invoke the transaction, transferring control completely. 46 47 new_path = parts[0:1] + (parts[2:] or [""]) 48 new_path_info = "/".join(new_path) 49 trans.set_virtual_path_info(new_path_info) 50 51 if resource is not None: 52 resource.respond(trans) 53 return 54 55 # Otherwise, signal an error. 56 57 self.send_error(trans) 58 59 def send_error(self, trans): 60 61 "Send the error using the given 'trans'." 62 63 trans.set_response_code(404) 64 trans.set_content_type(WebStack.Generic.ContentType("text/plain")) 65 out = trans.get_response_stream() 66 out.write("Resource '%s' not found." % trans.get_path_info()) 67 68 # vim: tabstop=4 expandtab shiftwidth=4