Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community!

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Flask Basics Welcome to Flask Clean URL Arguments

Add routes to implement "int + int", "int + float", "float + int" and "float + float". Simple method?

I need some help in trying to write routes to implement additions where each argument can be either int or float. One obvious way is to write 4 different routes to handle different types.

For example, the following codes

@app.route('/add/<int:num1>/<int:num2>') def addints(num1,num2): return "{} + {} = {}".format(num1,num2,num1+num2)

@app.route('/add/<float:num1>/<float:num2>') def addfloats(num1,num2): return "{} + {} = {}".format(num1,num2,num1+num2)

@app.route('/add/<int:num1>/<float:num2>') def addintfloat(num1,num2): return "{} + {} = {}".format(num1,num2,num1+num2)

can handle "int+int", "float+float" and "int+float". However, if I enter endpoint: /add/6.5/4, I got 404... Of course I can add yet another route to handle it, but I've pretty fed up with this hard-coding style. Is there a better way to manage all 4 possibilities by setting up the url?

Thanks very much!

1 Answer

John Lack-Wilson
John Lack-Wilson
8,181 Points

You're absolutely right, we want to use the DRY principle.

You can specify one singular route i.e. @app.route('/add/<num1>/<num2>') - notice I'm not specifying parameter types here.

Then we can check if the parameters are floats or not - see here

If they are floats then we can use the float(variable) function to convert it to a float. If they are not floats we can use the int(variable) function.

Then you can do your addition. Also, don't worry about adding floats and integers together - if Python sees a float adding with an int, it will return a float.

Note you should also do some basic error handling for if the parameters are neither an int or a float to avoid odd results.

Wonderful! Thanks very much! Right, I agree that using the power of python may be the best solution.