My application catches all url requests with an @app.route
, but occasionally I bump into a bad url for which I have no matching jinja file (bu it does match an existing @app.route
). So I want to redirect such requests to a 404 page for that bad url.
How to discriminate between "a jinja file exists" and "a jinja file doesn't exist" before returning render_template()
?
Jinja will throw an exception if the template is not found: TemplateNotFound
So instead of:
def myview():return render_template(...)
you could do something like this:
def myview():try:return render_template(...)except TemplateNotFound:abort(404)
And then handle the 404 error with a custom error page as explained in the Flask documentation. Don't forget to import abort
from flask
and TemplateNotFound
from jinja2