Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Flask custom 404 page using errorhandler

If we don’t have any special configuration for handling 404 pages, then we’ll see the default 404 pages generated by Flask.

from flask import Flask
app = Flask(__name__)

@app.route("/")
def main():
    return 'Main <a href="/not">404 page</a>'

We can designate one of the function to be the errorhandler for 404 errors. Every time Flask reaches the conclusion that the requested page does not exist, it will call this function.

from flask import Flask
app = Flask(__name__)

@app.route("/")
def main():
    return 'Main <a href="/not">404 page</a>'

@app.errorhandler(404)
def not_found(err):
    return f"Design your own 'Not found' page! {err}", 404
curl -I http://localhost:5000/not

HTTP/1.0 404 NOT FOUND

Testing the examples

import default_404

def test_main_page():
    web = default_404.app.test_client()

    rv = web.get('/')
    assert rv.status == '200 OK'
    assert rv.data.decode('utf-8') == 'Main <a href="/not">404 page</a>'

def test_missing_page():
    web = default_404.app.test_client()

    rv = web.get('/not')
    assert rv.status == '404 NOT FOUND'
    assert '<title>404 Not Found</title>' in rv.data.decode('utf-8')
    assert '<h1>Not Found</h1>' in rv.data.decode('utf-8')
    assert '<p>The requested URL was not found on the server.' in rv.data.decode('utf-8')

import handle_404

def test_main_page():
    web = handle_404.app.test_client()

    rv = web.get('/')
    assert rv.status == '200 OK'
    assert rv.data.decode('utf-8') == 'Main <a href="/not">404 page</a>'

def test_missing_page():
    web = handle_404.app.test_client()

    rv = web.get('/not')
    assert rv.status == '404 NOT FOUND'
    assert "Design your own 'Not found' page!" in rv.data.decode('utf-8')
    assert 'The requested URL was not found on the server.' in rv.data.decode('utf-8')