🎓 A1Learner
🔍
0 of 50 lessons completed

Aborting Flask Requests

abort stops a view with an error at once. The view raises the error instead of returning a page.

Make the app

This line imports Flask and abort together. The dict below holds the known pages.

from flask import Flask, abort

app = Flask(__name__)

pages = {"about": "About this site", "help": "Help page"}

Abort for unknown pages

The view looks the name up in the dict. A missing name aborts with a 404.

@app.route("/page/<name>")
def page(name):
    if name not in pages:
        abort(404)
    return pages[name]

The 404 handler

This view runs when abort raises the 404. It returns a plain message and the code.

@app.errorhandler(404)
def not_found(error):
    return "That page does not exist", 404

Ask for a known page and a missing one

The first ask finds the about page. The second ask aborts, and the handler page shows.

client = app.test_client()
print(client.get("/page/about").data.decode())
print(client.get("/page/missing").data.decode())

Example

from flask import Flask, abort

app = Flask(__name__)

pages = {"about": "About this site", "help": "Help page"}

@app.route("/page/<name>")
def page(name):
    if name not in pages:
        abort(404)
    return pages[name]

@app.errorhandler(404)
def not_found(error):
    return "That page does not exist", 404

client = app.test_client()
print(client.get("/page/about").data.decode())
print(client.get("/page/missing").data.decode())

Key points

  • abort(404) stops the view with a 404.
  • Use abort when the asked-for item does not exist.
  • abort(403) stops the view with a forbidden error.
  • The error page comes from the error handler.

In this example, the view looks the page name up in a dict. The name about is there, so the page shows. The name missing is not there, so abort(404) stops the view. The 404 handler then returns its message, and the prints show both pages.

Note

abort raises an error, so lines after it never run.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

When should a view call abort(404)?