Can Flask have optional URL parameters?
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Hypnotic Puzzle4
--
Chapters
00:00 Question
00:28 Accepted answer (Score 474)
00:50 Answer 2 (Score 231)
01:13 Answer 3 (Score 89)
01:34 Answer 4 (Score 32)
01:48 Thank you
--
Full question
https://stackoverflow.com/questions/1403...
Answer 3 links:
https://flask.palletsprojects.com/en/1.1...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #flask
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Hypnotic Puzzle4
--
Chapters
00:00 Question
00:28 Accepted answer (Score 474)
00:50 Answer 2 (Score 231)
01:13 Answer 3 (Score 89)
01:34 Answer 4 (Score 32)
01:48 Thank you
--
Full question
https://stackoverflow.com/questions/1403...
Answer 3 links:
https://flask.palletsprojects.com/en/1.1...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #flask
#avk47
ACCEPTED ANSWER
Score 491
Another way is to write
@user.route('/<user_id>', defaults={'username': None})
@user.route('/<user_id>/<username>')
def show(user_id, username):
pass
But I guess that you want to write a single route and mark username as optional? If that's the case, I don't think it's possible.
ANSWER 2
Score 247
Almost the same as Audrius cooked up some months ago, but you might find it a bit more readable with the defaults in the function head - the way you are used to with python:
@app.route('/<user_id>')
@app.route('/<user_id>/<username>')
def show(user_id, username='Anonymous'):
return user_id + ':' + username
ANSWER 3
Score 90
If you are using Flask-Restful like me, it is also possible this way:
api.add_resource(UserAPI, '/<userId>', '/<userId>/<username>', endpoint = 'user')
a then in your Resource class:
class UserAPI(Resource):
def get(self, userId, username=None):
pass
ANSWER 4
Score 36
@user.route('/<userId>/') # NEED '/' AFTER LINK
@user.route('/<userId>/<username>')
def show(userId, username=None):
pass
https://flask.palletsprojects.com/en/1.1.x/quickstart/#unique-urls-redirection-behavior