How to validate integer range in Flask routing (Werkzeug)? How to validate integer range in Flask routing (Werkzeug)? flask flask

How to validate integer range in Flask routing (Werkzeug)?


Flask uses the Werkzeug routing system, after I checked the Werkzeug URL Routing docs, I find it's possible to do range control in route rules.

From Werkzeug docs

class werkzeug.routing.IntegerConverter(map, fixed_digits=0, min=None, max=None)

So, you can set the keyword arguments min and max in the route rule like this:

@app.route("/foo/<int(min=1, max=300):id>")

If id is out of range, the request will get a response 404.

Hope this helps.


EDIT for the comment :

So there are two options to the range validation

  1. in the routing
  2. in the get_foo method

I think the choice depends on your own situation.

The first option will response 404 immediately if id is out of range, as mentioned above.

In the second way, you can validate the range of id, and do something you like to deal with the bad requests.