[Twisted-Python] Serving files, again

Clark C. Evans cce at clarkevans.com
Wed Feb 26 14:48:52 EST 2003

On Wed, Feb 26, 2003 at 12:48:31AM +0100, Mario Ruggier wrote:
| Oh, and in general, how does one turn off directory browsing
| for a twisted.web server?

You could do this in the constructor,

    path = RestrictedResource('/my/path',directoryBrowsing=false)

But, this really should be done on a per-request mechanism.  Perhaps
request needs a "options" collection where a top-level Resource 
can set processing options for lower-level resources in the path
chain (see the FilterResource post previously).

Anyway, I wanted to respond to your code below...

| class RestrictedResource(resource.Resource):
|     def isLeaf(self):
|         return 1
|     def render(self, request):
|         fullPath = docsBase +'/'+ subPath
|         try:
|             if not os.path.exists(fullPath):
|                 raise Exception # of type...
|             elif os.path.isdir(fullPath):
|                 dirlist = processDirlist(os.listdir(fullPath))
|             elif os.path.isfile(fullPath):
|                 import mimetypes

This is interesting.  I would have probably done it a less
efficient way (but perhaps more flexible)?  I would have 
used two resources, a DirectoryResource and a FileResource.  

The DirectoryResource would override getChild(path,request) and 
dynamically look for a child in the current path, leveraging the
descent operation in getChildForRequest.  This object would then
either return the subordinate NotFoundResource, DirectoryResource 
or a FileResource object depending on what the path matched. 
The constructor for these child resources would have a fullpath,
constructed by concatinating the fullpath of the current Directory
with the given path.

The FileResource would serve up the given file, by overriding
the render(request) method as you have specified above.  In this
way one could provide a replacement FileResource or override a
DirectoryResource, etc.  

If you wanted to get tricky, you could "stuff" the path state
into the request object and the DirectoryResource could 
'return self' instead of creating intermediary Directories.
This leads to the following more general questions:

  1.  There should be a general way to attach "resource specific"
      data to a given request, for DirectoryResource it'd be the
      current path, for PathArgs, it'd be the mapping of path
      arguments to variables.

  2.  This mechanism could thus be used for inter-resource 
      communication, say where a UserSession(FilterResource)
      would attach a directive to "compress_files" or not
      to subordinate FileResources.

As I said in a previous post, I'm quite impressed with the
whole "Resource" concept and the "tail recursive" descent
mechanism provided via getChildForRequest.

Hope this helps...


More information about the Twisted-Python mailing list