🎓 A1Learner
🔍
0 of 50 lessons completed

Handling Flask 404 Errors

A 404 page answers an unknown address. The errorhandler decorator marks a view for that error.

Make the app

This line imports Flask and render_template_string together. The routes below belong to the app.

from flask import Flask, render_template_string

app = Flask(__name__)

The home route

This route returns the home page.

@app.route("/")
def home():
    return "Home page"

The 404 handler

This view runs for every missing address. It returns the page and the code 404 together.

@app.errorhandler(404)
def not_found(error):
    return render_template_string("<h1>Page not found</h1>"), 404

Ask for a missing page

The test client asks for /nope, which has no route. The prints show the 404 status and the page.

client = app.test_client()
print(client.get("/nope").status_code)
print(client.get("/nope").data.decode())

Example

from flask import Flask, render_template_string

app = Flask(__name__)

@app.route("/")
def home():
    return "Home page"

@app.errorhandler(404)
def not_found(error):
    return render_template_string("<h1>Page not found</h1>"), 404

client = app.test_client()
print(client.get("/nope").status_code)
print(client.get("/nope").data.decode())

Key points

  • @app.errorhandler(404) marks the view for missing pages.
  • The view takes the error as its argument.
  • Return the page and 404 together.
  • Every unknown address shows the same page.

In this example, the app has one route and one 404 handler. The handler takes the error and returns a page with the code 404. The test client asks for /nope, which has no route, and the prints show the 404 status and the page.

Note

The handler only runs for that one error code.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What marks a view as the handler for missing pages?