durusmail: quixote-users: Module to map static files into Quixote
Module to map static files into Quixote
2002-09-23
2002-09-23
Module to map static files into Quixote
Hamish Lawson
2002-09-23
Sometimes it may be convenient to let Quixote itself deal with static files
when they are part of the same URL space as the dynamic content. I've
enclosed a module to map static files into Quixote. Here are a couple of
usage examples (assuming filesystem_base_path has been set appropriately).

Mapping a complete filesytem folder containing static files:

     notes = FilesystemFolder(os.path.join(filesystem_base_path, 'notes'))

Mapping an individual filesystem file. (Because 'stylesheet.css' isn't a
valid identifier name, we need to use setattr to set it as an attribute of
the current module.)

     filepath = os.path.join(filesystem_base_path, 'stylesheet.css')
     setattr(sys.modules[__name__], 'stylesheet.css', FilesystemFile(filepath))


Hamish Lawson


=== filesystem.py ===========================================================

import quixote, os, mimetypes


class FilesystemFile:

     """
     Represents a file on the filesystem as a callable instance. The MIME
     type of the resulting response is computed from the file's extension.
     """

     def __init__(self, path):
         self.path = path
         self.mimetype = mimetypes.guess_type(os.path.basename(self.path),
0)[0]
         f = open(self.path)
         self.contents = f.read()
         f.close()

     def __call__(self, request):
         request.response.set_header('Content-Type', self.mimetype)
         return self.contents


class FilesystemFolder:

     """
     Represents a folder on the filesystem as a Quixote namespace. Items in
the
     folder are found through _q_getname, and can result in either
FilesystemFile
     or FilesystemFolder instances. A basic index page can be generated,
listing
     the contents of the folder."
     """

     _q_exports = []

     def __init__(self, path):
         self.path = path

     def _q_index(self, request):
         output = []
         output.append("

%s

" % request.environ['REQUEST_URI']) for filename in os.listdir(self.path): filepath = os.path.join(self.path, filename) indicator = os.path.isdir(filepath) and "/" or "" output.append( '

%(filename)s%(indicator)s' % locals() ) return "\n".join(output) def _q_getname(self, request, name): filepath = os.path.join(self.path, name) if os.path.exists(filepath): if os.path.isdir(filepath): return FilesystemFolder(filepath) else: return FilesystemFile(filepath)(request) else: raise quixote.errors.TraversalError(name)

reply