Flask route giving 404 with floating point numbers in the URL

Question:

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?

Asked By: tldr

||

Answers:

The built-in FloatConverter has a signed argument that can enable matching signed values.

@app.route("/nearby/<float(signed=True):lat>/<float(signed=True):long>

Prior to Werkzeug 0.15, the built-in converter did not handle negative numbers. Write a custom converter to handle negatives. This converter also treats integers as floats, which also would have failed. The built-in doesn’t handle integers because then /1 and /1.0 would point to the same resource, but for the positions you’re trying to match that probably doesn’t matter.

from werkzeug.routing import FloatConverter as BaseFloatConverter

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

# before routes are registered
app.url_map.converters['float'] = FloatConverter
Answered By: davidism

Since the built in FloatConverter can only handle positive numbers, I pass the coordinates as strings, and use Python’s float() method to convert them to floats.

Answered By: tldr

As of Werkzeug 0.15 the built-in float converter has a signed=True parameter, which you can use for this:

@app.route('/nearby/<float(signed=True):lat>/<float(signed=True):long>')
Answered By: Pieter Ennes