5

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)
  • Does this answer your question? [Can Flask have optional URL parameters?](https://stackoverflow.com/questions/14032066/can-flask-have-optional-url-parameters) – andrew_reece Nov 28 '19 at 02:19

2 Answers2

15

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

Ankur
  • 308
  • 1
  • 5
arshovon
  • 13,270
  • 9
  • 51
  • 69
-1

Try this one

@win.route("/<name>/<int:ints>/<float:floats>")
def web(name, ints=None, floats=None):
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)
Tahir
  • 1