route logic for trailing slash

This commit is contained in:
Raphael Deem 2017-02-20 15:58:27 -08:00
parent ff5d4276bc
commit 207ec1e032
3 changed files with 30 additions and 1 deletions

View File

@ -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

View File

@ -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

View File

@ -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')