From 207ec1e0322776cd795739a8ce1acf390e8b6888 Mon Sep 17 00:00:00 2001 From: Raphael Deem Date: Mon, 20 Feb 2017 15:58:27 -0800 Subject: [PATCH] route logic for trailing slash --- sanic/app.py | 3 +++ sanic/router.py | 15 ++++++++++++++- tests/test_routes.py | 13 +++++++++++++ 3 files changed, 30 insertions(+), 1 deletion(-) diff --git a/sanic/app.py b/sanic/app.py index ea45293a..4155e870 100644 --- a/sanic/app.py +++ b/sanic/app.py @@ -270,6 +270,9 @@ class Sanic: 'Endpoint with name `{}` was not found'.format( view_name)) + if uri.endswith('/'): + uri = uri[:-1] + out = uri # find all the parameters we will need to build in the URL diff --git a/sanic/router.py b/sanic/router.py index 4de95cb2..44ab9964 100644 --- a/sanic/router.py +++ b/sanic/router.py @@ -96,6 +96,20 @@ class Router: return name, _type, pattern def add(self, uri, methods, handler, host=None): + # add regular version + self._add(uri, methods, handler, host) + slash_is_missing = (not uri[-1].endswith('/') + and not self.routes_all.get(uri + '/', False)) + without_slash_is_missing = (not self.routes_all.get(uri[:-1], False) + and uri is not '/') + # add version with trailing slash + if slash_is_missing: + self._add(uri + '/', methods, handler, host) + # add version without trailing slash + elif without_slash_is_missing: + self._add(uri[:-1], methods, handler, host) + + def _add(self, uri, methods, handler, host=None): """Add a handler to the route list :param uri: path to match @@ -105,7 +119,6 @@ class Router: When executed, it should provide a response object. :return: Nothing """ - if host is not None: if isinstance(host, str): uri = host + uri diff --git a/tests/test_routes.py b/tests/test_routes.py index 12371e57..d9e4532f 100644 --- a/tests/test_routes.py +++ b/tests/test_routes.py @@ -22,6 +22,19 @@ def test_shorthand_routes_get(): request, response = app.test_client.post('/get') assert response.status == 405 +def test_route_optional_slash(): + app = Sanic('test_route_optional_slash') + + @app.get('/get') + def handler(request): + return text('OK') + + request, response = app.test_client.get('/get') + assert response.text == 'OK' + + request, response = app.test_client.get('/get/') + assert response.text == 'OK' + def test_shorthand_routes_post(): app = Sanic('test_shorhand_routes_post')