From 638a151d96d681d3bdd6ba5ce5dcf2bd1447959c Mon Sep 17 00:00:00 2001 From: Matthew Graham Date: Sat, 9 Oct 2010 15:27:13 -0400 Subject: [PATCH] make StaticFileHandler support default filename 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 | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/tornado/web.py b/tornado/web.py index 09ea49ab5..9c75d7f4a 100644 --- a/tornado/web.py +++ b/tornado/web.py @@ -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): -- 2.47.2