From: Matthew Graham Date: Sat, 9 Oct 2010 19:27:13 +0000 (-0400) Subject: make StaticFileHandler support default filename X-Git-Tag: v1.2.0~98^2 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=refs%2Fpull%2F151%2Fhead;p=thirdparty%2Ftornado.git 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. --- 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):