1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/WebStack/Resources/ResourceMap.py Sat Feb 19 14:01:49 2005 +0000
1.3 @@ -0,0 +1,70 @@
1.4 +#!/usr/bin/env python
1.5 +
1.6 +"Mapping from names to resources."
1.7 +
1.8 +import WebStack.Generic
1.9 +
1.10 +class MapResource:
1.11 +
1.12 + "A resource mapping names to other resources."
1.13 +
1.14 + def __init__(self, mapping):
1.15 +
1.16 + """
1.17 + Initialise the resource with a 'mapping' of names to resources. The
1.18 + 'mapping' should be a dictionary-like object employing simple names
1.19 + without "/" characters; the special value None is used where no name
1.20 + is found in the request path.
1.21 + """
1.22 +
1.23 + self.mapping = mapping
1.24 +
1.25 + def respond(self, trans):
1.26 +
1.27 + """
1.28 + Using the path information from the given transaction 'trans', invoke
1.29 + mapped resources. Otherwise return an error condition.
1.30 + """
1.31 +
1.32 + # Get the path info.
1.33 +
1.34 + parts = trans.get_path_info().split("/")
1.35 +
1.36 + # The first part should always be empty.
1.37 +
1.38 + if len(parts) > 1:
1.39 + name = parts[1]
1.40 + else:
1.41 + name = None
1.42 + print "*", name
1.43 +
1.44 + # Get the mapped resource.
1.45 +
1.46 + resource = self.mapping.get(name)
1.47 + print "**", resource
1.48 +
1.49 + # If a resource was found, change the transaction's path info, then
1.50 + # invoke the transaction, transferring control completely.
1.51 +
1.52 + new_path_info = "/".join(parts[0:1] + parts[2:])
1.53 + print "***", new_path_info
1.54 + trans.set_path_info(new_path_info)
1.55 +
1.56 + if resource is not None:
1.57 + resource.respond(trans)
1.58 + return
1.59 +
1.60 + # Otherwise, signal an error.
1.61 +
1.62 + self.send_error(trans)
1.63 +
1.64 + def send_error(self, trans):
1.65 +
1.66 + "Send the error using the given 'trans'."
1.67 +
1.68 + trans.set_response_code(404)
1.69 + trans.set_content_type(WebStack.Generic.ContentType("text/plain"))
1.70 + out = trans.get_response_stream()
1.71 + out.write("Resource '%s' not found." % trans.get_path_info())
1.72 +
1.73 +# vim: tabstop=4 expandtab shiftwidth=4