Is it possible to directly declare a flask URL optional parameter?
Currently I'm proceeding the following way:
@user.route('/<userId>') @user.route('/<userId>/<username>') def show(userId, username=None): pass
How can I directly say that username
is optional?
Parameters provide a way of passing arbitrary data to a page via the URL. Optional parameters allow URLs to matched to routes even if no parameter value is passed. Things can get a bit complicated if you want to permit multiple optional parameters.
You can define Python function optional arguments by specifying the name of an argument followed by a default value when you declare a function. You can also use the **kwargs method to accept a variable number of arguments in a function. To learn more about coding in Python, read our How to Learn Python guide.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With