1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/WebStack/Resources/Static.py Mon May 02 18:52:52 2005 +0000
1.3 @@ -0,0 +1,78 @@
1.4 +#!/usr/bin/env python
1.5 +
1.6 +"""
1.7 +Resources for serving static content.
1.8 +"""
1.9 +
1.10 +from WebStack.Generic import ContentType, EndOfResponse
1.11 +import os
1.12 +
1.13 +class DirectoryResource:
1.14 +
1.15 + "A resource serving the contents of a filesystem directory."
1.16 +
1.17 + def __init__(self, directory, media_types=None, unrecognised_media_type="application/data"):
1.18 +
1.19 + """
1.20 + Initialise the resource to serve files from the given 'directory'.
1.21 +
1.22 + The optional 'media_types' dictionary can be used to map filename
1.23 + extensions to media types, where extensions consist of the part of a
1.24 + name after a "." character (such as "txt", "html"), and where media
1.25 + types are the usual content descriptions (such as "text/plain" and
1.26 + "text/html").
1.27 +
1.28 + If 'media_types' contains a mapping from None to a media type, then
1.29 + this mapping is used when no extension is present on a requested
1.30 + resource name.
1.31 +
1.32 + Where no media type can be found for a resource, a predefined media
1.33 + type is set which can be overridden by specifying a value for the
1.34 + optional 'unrecognised_media_type' parameter.
1.35 + """
1.36 +
1.37 + self.directory = directory
1.38 + self.media_types = media_types or {}
1.39 + self.unrecognised_media_type = unrecognised_media_type
1.40 +
1.41 + def respond(self, trans):
1.42 +
1.43 + "Respond to the given transaction, 'trans', by serving a file."
1.44 +
1.45 + parts = trans.get_virtual_path_info().split("/")
1.46 + filename = parts[1]
1.47 + out = trans.get_response_stream()
1.48 +
1.49 + # Test for the file's existence.
1.50 +
1.51 + pathname = os.path.join(self.directory, filename)
1.52 + if not (os.path.exists(pathname) and os.path.isfile(pathname)):
1.53 + trans.set_response_code(404)
1.54 + trans.set_content_type(ContentType("text/plain"))
1.55 + out.write("Resource '%s' not found." % filename)
1.56 + raise EndOfResponse
1.57 +
1.58 + # Get the extension.
1.59 +
1.60 + extension_parts = filename.split(".")
1.61 +
1.62 + if len(extension_parts) > 1:
1.63 + extension = extension_parts[-1]
1.64 + media_type = self.media_types.get(extension)
1.65 + else:
1.66 + media_type = self.media_types.get(None)
1.67 +
1.68 + # Set the content type.
1.69 +
1.70 + if media_type is not None:
1.71 + trans.set_content_type(ContentType(media_type))
1.72 + else:
1.73 + trans.set_content_type(ContentType(self.unrecognised_media_type))
1.74 +
1.75 + # Write the file to the client.
1.76 +
1.77 + f = open(os.path.join(self.directory, filename), "rb")
1.78 + out.write(f.read())
1.79 + f.close()
1.80 +
1.81 +# vim: tabstop=4 expandtab shiftwidth=4