Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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,168 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.