]> git.ipfire.org Git - thirdparty/tornado.git/commitdiff
Add addslash and removeslash decorators for, e.g., redirecting '/dir' to '/dir/'
authorBret Taylor <btaylor@gmail.com>
Sun, 13 Sep 2009 21:13:55 +0000 (14:13 -0700)
committerBret Taylor <btaylor@gmail.com>
Sun, 13 Sep 2009 21:13:55 +0000 (14:13 -0700)
tornado/web.py

index aeea60c83aec717531bb44853102f607bb12fe9e..c4d8701198e95e48175064078bbb6dead10e054c 100644 (file)
@@ -775,6 +775,46 @@ def asynchronous(method):
     return wrapper
 
 
+def removeslash(method):
+    """Use this decorator to remove trailing slashes from the request path.
+
+    For example, a request to '/foo/' would redirect to '/foo' with this
+    decorator. Your request handler mapping should use a regular expression
+    like r'/foo/*' in conjunction with using the decorator.
+    """
+    @functools.wraps(method)
+    def wrapper(self, *args, **kwargs):
+        if self.request.path.endswith("/"):
+            if self.request.method == "GET":
+                uri = self.request.path.rstrip("/")
+                if self.request.query: uri += "?" + self.request.query
+                self.redirect(uri)
+                return
+            raise HTTPError(404)
+        return method(self, *args, **kwargs)
+    return wrapper
+
+
+def addslash(method):
+    """Use this decorator to add a missing trailing slash to the request path.
+
+    For example, a request to '/foo' would redirect to '/foo/' with this
+    decorator. Your request handler mapping should use a regular expression
+    like r'/foo/?' in conjunction with using the decorator.
+    """
+    @functools.wraps(method)
+    def wrapper(self, *args, **kwargs):
+        if not self.request.path.endswith("/"):
+            if self.request.method == "GET":
+                uri = self.request.path + "/"
+                if self.request.query: uri += "?" + self.request.query
+                self.redirect(uri)
+                return
+            raise HTTPError(404)
+        return method(self, *args, **kwargs)
+    return wrapper
+
+
 class Application(object):
     """A collection of request handlers that make up a web application.