Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask route giving 404 with floating point numbers in the URL

I have the following route definition in my Flask app's server.py:

@app.route('/nearby/<float:lat>/<float:long>')
def nearby(lat, long):
    for truck in db.trucks.find({'loc': {'$near': [lat, long]}}).limit(5):
        if truck.has_key('loc'):
            del truck['loc']
    return json.dumps(trucks)

But when I go to http://localhost:5000/nearby/37.7909470419234/-122.398633589404, I get a 404.

The other routes work fine, so it's an issue with this one. What am I doing wrong here?

like image 286
tldr Avatar asked Dec 17 '13 16:12

tldr


People also ask

How do I link my URL to my flask?

We can use the url_for() function to generate the links in the following way. Flask knows the mapping between URLs and functions so it will generate the /login and /profile URLs for us. This makes the application maintainable because if you want to change the URL, all you need to change the app.

What is URL routing in flask?

App routing is used to map the specific URL with the associated function that is intended to perform some task. It is used to access some particular page like Flask Tutorial in the web application.

Can you use multiple decorators to route URLs to a function in flask?

We can use multiple decorators by stacking them.


1 Answers

The built-in FloatConverter does not handle negative numbers. Write a custom converter to handle negatives. This converter also treats integers as floats, which also would have failed.

from werkzeug.routing import FloatConverter as BaseFloatConverter

class FloatConverter(BaseFloatConverter):
    regex = r'-?\d+(\.\d+)?'

# before routes are registered
app.url_map.converters['float'] = FloatConverter

The built-in doesn't handle integers because then /1 and /1.0 would point to the same resource. Why it doesn't handle negative values is less clear.

like image 103
davidism Avatar answered Oct 22 '22 04:10

davidism