python - route - get query from url flask

Can Flask have optional URL parameters? (7)

Is it possible to directly declare a flask URL optional parameter?

Currently I'm proceeding the following way:

def show(userId, username=None):

Is there anything that can allow me to directly say that "username" is optional?

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:

def show(user_id, username='Anonymous'):
    return user_id + ':' + username

Another way is to write

@user.route('/<user_id>', defaults={'username': None})
def show(user_id, username):

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.

I think you can use Blueprint and that's will make ur code look better and neatly.


from flask import Blueprint

bp = Blueprint(__name__, "example")

@bp.route("/example", methods=["POST"])
def example(self):

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):

You can write as you show in example, but than you get build-error.

For fix this:

  1. print app.url_map () in you root .py
  2. you see something like:

<Rule '/<userId>/<username>' (HEAD, POST, OPTIONS, GET) -> user.show_0>


<Rule '/<userId>' (HEAD, POST, OPTIONS, GET) -> .show_1>

  1. than in template you can {{ url_for('.show_0', args) }} and {{ url_for('.show_1', args) }}

@user.route('/<user_id>', defaults={'username': default_value})
def show(user_id, username):