Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Flask have optional URL parameters?

Tags:

python

flask

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?

like image 310
Noor Avatar asked Dec 25 '12 15:12

Noor


People also ask

Can URL parameters be 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.

How do you make an argument optional in Python?

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.


2 Answers

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.

like image 106
Audrius Kažukauskas Avatar answered Sep 29 '22 03:09

Audrius Kažukauskas


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 
like image 45
mogul Avatar answered Sep 29 '22 01:09

mogul