Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a 404 page?

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()?

like image 940
hof0w Avatar asked Jun 12 '12 09:06

hof0w


People also ask

How do I get a 404 error page?

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.

What is a custom 404 page?

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.

What is HTML 404 page?

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.


1 Answers

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

like image 191
mensi Avatar answered Sep 21 '22 00:09

mensi