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?
Flask Form Validation With Flask-WTForms The GET method displays the form, whereas the POST method processes the form data on submission. We set the URL path to / , or the root URL, so it will appear as our web app's home page. We render the index. html template and pass the form object as a parameter.
Routing in FlaskThe route() decorator in Flask is used to bind an URL to a function. As a result when the URL is mentioned in the browser, the function is executed to give the result. Here, URL '/hello' rule is bound to the hello_world() function.
The validate_on_submit() method of the form returns True when the form was submitted and the data was accepted by all the field validators. In all other cases, validate_on_submit() returns False . The return value of this method effectively serves to determine whether the form needs to be rendered or processed.
App Routing means mapping the URLs to a specific function that will handle the logic for that URL. Modern web frameworks use more meaningful URLs to help users remember the URLs and make navigation simpler. Example: In our application, the URL (“/”) is associated with the root URL.
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
get_foo
methodI 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With