Question

I have the below routing in my flask app

from foo import get_foo

@app.route("/foo/<int:id>")
def foo_id(id):
    return render_template('foo.html', foo = get_foo(id))

Foo can have ID between 1-300. Where can I have this validation?

I can have the validation inside get_foo. But, I am not sure if it's best practice. Should I filter it in the route definition itself?

Something like @app.route("/foo/<int:id(1-300)") (I don't know the exact way to do this.

How do I accomplish my need?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top