]> git.ipfire.org Git - thirdparty/tornado.git/commitdiff
make StaticFileHandler support default filename 151/head 155/head
authorMatthew Graham <mdg149@gmail.com>
Sat, 9 Oct 2010 19:27:13 +0000 (15:27 -0400)
committerMatthew Graham <mdg149@gmail.com>
Sat, 16 Oct 2010 03:02:54 +0000 (23:02 -0400)
allows an app to configure a handler so that if a request to '/dir', the
handler will return '/dir/index.html' if it exists.  the default
filename, the 'index.html' part is configurable when creating the
Handler object.  Using the default filename is optional.

tornado/web.py

index 09ea49ab5ca5d74e0b17edc40e35b96718b02d24..9c75d7f4a80c4b1946c57bc89d5b422cfa3f0be4 100644 (file)
@@ -1227,17 +1227,28 @@ class StaticFileHandler(RequestHandler):
     want browsers to cache a file indefinitely, send them to, e.g.,
     /static/images/myimage.png?v=xxx.
     """
-    def __init__(self, application, request, path):
+    def __init__(self, application, request, path, default_filename=None):
         RequestHandler.__init__(self, application, request)
         self.root = os.path.abspath(path) + os.path.sep
+        self.default_filename = default_filename
 
     def head(self, path):
         self.get(path, include_body=False)
 
     def get(self, path, include_body=True):
         abspath = os.path.abspath(os.path.join(self.root, path))
-        if not abspath.startswith(self.root):
+        # os.path.abspath strips a trailing /
+        # it needs to be temporarily added back for requests to root/
+        if not (abspath + os.path.sep).startswith(self.root):
             raise HTTPError(403, "%s is not in root static directory", path)
+        if os.path.isdir(abspath) and self.default_filename is not None:
+            # need to look at the request.path here for when path is empty
+            # but there is some prefix to the path that was already
+            # trimmed by the routing
+            if not self.request.path.endswith(os.path.sep):
+                self.redirect(self.request.path + os.path.sep)
+                return
+            abspath = os.path.join(abspath, self.default_filename)
         if not os.path.exists(abspath):
             raise HTTPError(404)
         if not os.path.isfile(abspath):