Handlers with path variables are used even if parent route exists
See original GitHub issueDescribe the bug
Prior to Sanic 21, a route handler for /foo/
would be used instead of one for /foo/<var>/
if a request was made for GET /foo/
, but now the second handler is called with an empty string for <var>
.
Is this the intended behaviour - as in I should handle the case where the variable is empty instead of having a separate route? If so I’d have expected my example to throw a sanic_routing.exceptions.RouteExists
to prevent me making this mistake.
Code snippet
from sanic import Sanic
from sanic.response import json
app = Sanic("My Hello, world app")
@app.route('/foo/')
async def test(request):
return json({'hello': 'world'})
@app.route('/foo/<var>/')
async def myreq(request, var):
return json({'hello': var})
if __name__ == '__main__':
app.run()
Expected behavior Running the snippet above, I’d expect to see:
❯ curl localhost:8000/foo/bar/
{"hello":"bar"}%
❯ curl localhost:8000/foo/
{"hello":"world"}%
(which I what happens on sanic 20.12.3)
Instead I get (on 21.6.2 and also 21.3.0):
❯ curl localhost:8000/foo/bar/
{"hello":"bar"}%
❯ curl localhost:8000/foo/
{"hello":""}%
Environment (please complete the following information):
- OS: macOS Catalina 10.15.7
- Version: Sanic 21.6.2
- Python 3.7.9
Apologies if this should be on sanic_routing - I don’t really understand enough about the router to know!
Issue Analytics
- State:
- Created 2 years ago
- Comments:5 (4 by maintainers)
Top GitHub Comments
Brill, cheers for the detailed explanation, and clarifying that the old behaviour was the bug, rather than the new. I’d be inclined to agree with @Tronic that the manual should probably spend a few words on the implications of
strict_slashes
/some form of the very useful explanation in https://github.com/sanic-org/sanic/issues/2239#issuecomment-921330915 - it’s quite hard to find the forum post from cold! If nobody beats me to it I’ll drop a docs PR in when I get some time.Another example of why
strict_slashes
should always be enabled (in new projects). Maybe need to put some emphasis on that on the manual?I personally don’t ever expect web servers to do what the
strict_slashes=False
setting does. It could make sense to redirect a non-slashed request on a folder name to an URL with a trailing slash, but never to return the folder contents on an URL with a missing trailing slash. Also, the whole problem should exist only for manually typed in URLs.