changeset 25:511210365ce3

WIP getting paste StaticURLParser to serve directories
author Jeff Hammel <jhammel@mozilla.com>
date Wed, 29 Feb 2012 10:29:11 -0800
parents 13ed82d10144
children f8ff95180d04
files simpypi/factory.py
diffstat 1 files changed, 36 insertions(+), 1 deletions(-) [+]
line wrap: on
line diff
--- a/simpypi/factory.py	Wed Feb 29 09:16:48 2012 -0800
+++ b/simpypi/factory.py	Wed Feb 29 10:29:11 2012 -0800
@@ -20,8 +20,42 @@
     def __init__(self, directory):
         StaticURLParser.__init__(self, directory)
 
+    def index(self, directory):
+        """
+        generate a directory listing for a given directory
+        """
+        parts = ['<html><head><title>Simple Index</title></head><body>']
+        listings = os.listdir(directory)
+        listings = [(os.path.isdir(os.path.join(directory, entry)) and entry + '/' or entry, entry)
+                    for entry in listings]
+        for link, entry in listings:
+            parts.append('<a href="%s">%s</a><br/>' % (link, entry))
+        parts.append('</body></html>')
+        return '\n'.join(parts)
+
     def __call__(self, environ, start_response):
-        import pdb; pdb.set_trace()
+
+        # normalize path
+        # from paste.urlparser.StaticURLParser
+        path_info = environ.get('PATH_INFO', '')
+        if not path_info:
+            return self.add_slash(environ, start_response)
+        full = self.normpath(os.path.join(self.directory, path_info.strip('/')))
+        if not full.startswith(self.root_directory):
+            # Out of bounds
+            return self.not_found(environ, start_response)
+
+        # return index listing
+        if os.path.isdir(full):
+            if not path_info.endswith('/'):
+                return self.add_slash(environ, start_response)
+            index = self.index(full)
+            response_headers = [('Content-Type', 'text/html'),
+                                ('Content-Length', str(len(index)))]
+            start_response('200 OK', response_headers)
+            return [index]
+
+        return StaticURLParser.__call__(self, environ, start_response)
 
 class PassthroughFileserver(object):
     """serve files if they exist"""
@@ -47,6 +81,7 @@
     def __call__(self, environ, start_response):
         path = environ['PATH_INFO']
         if path == self.namespace:
+            return self.add_slash(environ, start_response)
             environ['PATH_INFO'] = '/'
             return DirectoryServer.__call__(self, environ, start_response)
         elif path.startswith(self.namespace + '/'):