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()
?
You'll get 404 errors if you've deleted or removed pages from your site recently without redirecting their URLs. 404 errors can also occur if you've relaunched or transferred your domain and failed to redirect all your old URLs to the new site. Sometimes 404 errors can be the result of changing a page's URL.
A custom 404 page takes away the confusion of not landing on the page they had intended to land on. It lets your user know that there is an error with their request. Perhaps they mistyped the URL, the page is temporarily unavailable, or the page no longer exists.
The HTTP 404 Not Found response status code indicates that the server cannot find the requested resource. Links that lead to a 404 page are often called broken or dead links and can be subject to link rot. A 404 status code only indicates that the resource is missing: not whether the absence is temporary or permanent.
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
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