Flask route giving 404 with floating point numbers in the URL

只谈情不闲聊 提交于 2019-12-01 15:30:33

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.

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.

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>')
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!