Sometimes, we want to add optional URL parameters with Python Flask
In this article, we’ll look at how to add optional URL parameters with Python Flask.
How to add optional URL parameters with Python Flask?
To add optional URL parameters with Python Flask, we can set the default value for URL parameters.
For instance, we write
@user.route('/<user_id>', defaults={'username': None})
@user.route('/<user_id>/<username>')
def show(user_id, username):
pass
to add the routes that map to the show
view.
We call the user.route
decorator with the route patterns that have the username
parameter and without.
And when we call route
with a URL without the username
parameter, we set username
to None
as the default value.
Conclusion
To add optional URL parameters with Python Flask, we can set the default value for URL parameters.