Merge pull request #470 from r0fls/url-slash
route logic for trailing slash
This commit is contained in:
commit
20b78b68a6
|
@ -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
|
||||
|
|
|
@ -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
|
||||
|
|
|
@ -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')
|
||||
|
||||
|
|
Loading…
Reference in New Issue
Block a user