Can Flask have optional URL parameters?
--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Hypnotic Orient Looping
--
Chapters
00:00 Can Flask Have Optional Url Parameters?
00:24 Accepted Answer Score 490
00:47 Answer 2 Score 245
01:09 Answer 3 Score 90
01:29 Answer 4 Score 35
01:44 Answer 5 Score 16
01:56 Thank you
--
Full question
https://stackoverflow.com/questions/1403...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #flask
#avk47
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Hypnotic Orient Looping
--
Chapters
00:00 Can Flask Have Optional Url Parameters?
00:24 Accepted Answer Score 490
00:47 Answer 2 Score 245
01:09 Answer 3 Score 90
01:29 Answer 4 Score 35
01:44 Answer 5 Score 16
01:56 Thank you
--
Full question
https://stackoverflow.com/questions/1403...
--
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