Python Flask Basics Welcome to Flask The Adder

chun chang
PRO
chun chang
Pro Student 1,390 Points

Is there a way to accept either one of different types for a argument?

as title

3 Answers

Andreas cormack
Andreas cormack
Python Web Development Techdegree Graduate 31,142 Points

do you mean pass different datatypes as arguments?

python
@app.route('/add/<int:num1>/<int:num2>')
@app.route('/add/<int:num1>/<float:num2>')
@app.route('/add/<float:num1>/<int:num2>')
@app.route('/add/<float:num1>/<float:num2>')
def add(num1,num2):
    return "{} + {} = {}".format(num1,num2,num1+num2)
chun chang
PRO
chun chang
Pro Student 1,390 Points

I wonder if there is any way that we can use to specify num1 can be either int or float in a single route instead of repeat for several routes

I would simply not specify what data type I wanted in the route. This would therefore give me string values, from there simply use a try except to accept both ints and floats.

Example:

@app.route("/add/<num1>/<num2>") # NOTE: This gets the values as strings
def add(num1, num2):
    num1 = getValue(num1) # Get int or float values for both
    num2 = getValue(num2)
    return "{} + {} = {}".format(num1, num2, num1 + num2)

def getValue(string):
    try:
        return int(string) # Attempt to return int value of string
    except ValueError: # If getting int value failed, then get float value
        return float(string)

Note:

The getValue() function was created to demonstrate the logic separately but it could have been added within

def add(num1, num2): 
```.
It is however cleaner and more importantly, reusable.