Issue
When I go to my (imaginary website), it works:
mywebsite.com/flowers
But if I add a "/" at the end, I get a "Not Found" error:
mywebsite.com/flowers/
Assuming my route is:
@app.route('/flowers', methods=['GET'])
def xyz():..
Am I supposed to redirect "/flowers/" to /"flowers" or am I supposed to add multiple routes? I'm not sure how it's supposed to work without copy-pasting my entire function for every (original route + "/").
Solution
In Flask, the URL redirection with and without trailing /
works differently.
@app.route('/works/')
def works():
return 'This works'
@app.route('/sorry')
def sorry():
return 'sorry'
The URL for the works
endpoint has a trailing slash. It’s similar to a folder in a file system. If you access the URL without a trailing slash (/works
), Flask redirects you to the URL with the trailing slash /works/
.
The URL for the sorry
endpoint does not have a trailing slash. It’s similar to the pathname of a file. Accessing the URL with a trailing slash /sorry/
produces a 404 "Not Found" error.
Alternatively, to make this works at the application level, You can use
app.url_map.strict_slashes = False
Setting strict_slashes
to False will work as expected with the /sorry/
route.
URL routes that end with a slash are branches, others are leaves. If strict_slashes
is enabled (the default), visiting a branch URL without a trailing slash will redirect to the URL with a slash appended.
Reference: Flask doc , Werkzeug Docs
Answered By - ShivaGaire
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.