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)
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:
Two parameters:
One parameter:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With