Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask - Optional path args

Tags:

python

flask

How can I make the path /name/int/float be optional.

So if I did: http://localhost/Zeref/ it would still work despite not inputting an int or float.

And if I did http://localhost/Zeref/1/ It will do just name and the int not the float.

So what can I do to make them optional?

Code:

import flask

win = flask.Flask(__name__)

@win.route("/<name>/<int:ints>/<float:floats>")

def web(name, ints, floats):
    return "Welcome Back: %s Your Int: %d Your Float: %f" % (name, ints, floats)

win.run("localhost", 80)
like image 965
Zeref Dragneel Avatar asked Dec 13 '22 13:12

Zeref Dragneel


1 Answers

Optional parameters are allowed in Flask.

You can define multiple rules for same function. Here is the documentation on URL Route Registrations.

Updated code:

import flask

win = flask.Flask(__name__)

@win.route('/<name>/', defaults={'ints': None, 'floats': None})
@win.route('/<name>/<int:ints>/', defaults={'floats': None})
@win.route("/<name>/<int:ints>/<float:floats>/")
def web(name, ints, floats):
    if ints!=None and floats!=None:
        return "Welcome Back: %s, Your Int: %d, Your Float: %f" % (name, ints, floats)
    elif ints!=None and floats==None:
        return "Welcome Back: %s, Your Int: %d" % (name, ints)
    return "Welcome Back: %s" % (name)

win.run(debug=True)

When chrome or any other web browser requests either of these URLs, Flask will invoke the associated function along with the arguments provided in the url. If no or less arguments are provided then default values of arguments will be used.

Screenshots:

Three parameters:

Three parameters

Two parameters:

Two parameters

One parameter:

One parameter

like image 70
arsho Avatar answered Dec 22 '22 17:12

arsho