Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 72 ยท Structure and Configuration

Hooks, Application Context and g

Run code before and after every request with Flask hooks, understand current_app and g, listen to signals, and add your own flask commands tested with test_cli_runner.

Some work has to happen on every request: starting a timer, opening a database connection, checking a maintenance flag, adding a header to every response. Copying that code into each view is tedious and easy to forget. Flask gives you hooks, functions you register once and Flask calls at fixed points in the life of a request.

Hooks pair with two helpers that let different parts of your code share data without passing arguments around: current_app, which points at the running application, and g, a scratch object that lives for one request. In this lesson you will learn which hook runs when, how the application context works, how to listen to Flask's signals, and how to add your own commands to the flask command line. If you want the bigger picture of how a request travels first, read How a request flows through Flask.

The request hooks

Flask has four decorators for the request life cycle. Here is the order they run in:

flowchart TD
    A["Request arrives"] --> B["before_request hooks<br/>(in registration order)"]
    B -->|"a hook returned a response"| D
    B -->|"all returned None"| C["View function"]
    C --> D["after_request hooks<br/>(reverse order)"]
    D --> E["Response sent to client"]
    E --> F["teardown_request hooks"]
    F --> G["teardown_appcontext hooks"]

If a before_request hook returns a response, the view is skipped, but after_request and teardown still run.

Decorator Runs Receives Must return
@app.before_request before the view nothing None to continue, or a response to stop
@app.after_request after the view, on the final response the response a response (usually the same one)
@app.teardown_request at the end of every request, even after errors the exception or None ignored
@app.teardown_appcontext when the application context is popped the exception or None ignored

Two rules are easy to forget. An after_request function must return a response, otherwise the client gets an error. A teardown_* function should never raise, and it is the right place for cleanup such as closing connections, because it runs even when the view crashed.

The next example uses all four. It gives each request a sequential id, blocks /admin without a header (a short-circuit), stamps the id on the response, and records teardown order in a list so you can see it.

Python Hooks in action

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Read the log: for the blocked /admin request you see before, then no view admin line, then after and teardown_request. The guard replaced the view's answer, but the response still went through after_request, so it carries an X-Request-Id header too.

If a view raises an exception that has an error handler (see Error handling), the handler produces a response and after_request still runs. An unhandled exception becomes a 500 response, which also passes through after_request (unless the exception is re-raised, as happens in debug and testing modes). In every case teardown_request runs and receives the exception.

Hooks on blueprints

A hook registered on a blueprint (bp.before_request) only runs for that blueprint's views. To run for the whole app from inside a blueprint, use bp.before_app_request. See Blueprints for the details.

The application context

Flask needs to know which app you mean when code asks "what is the current config?" or "where is the database connection?". It keeps that answer in the application context. Flask pushes an application context automatically for every request, and also for CLI commands. Two names exist only while a context is active:

  • current_app is a proxy to the app handling the work right now. Library code and blueprints use it instead of importing the app object, which avoids circular imports.
  • g is an empty object where you can store anything for the duration of the context, typically one request. Think of it as a per-request notepad.

Outside a context, both raise a RuntimeError. You can create one yourself with app.app_context(), which is how scripts and tests reach current_app and g.

Python current_app and g outside a request

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice that g does not survive between contexts: the second with block sees no total. That is the point. Data on g cannot leak from one request into the next. For data that must persist (a login, a cart) use the session; for data shared by all requests (a cache, a connection pool) use app.extensions or a module-level object.

Request context versus application context

A request also has its own request context, which provides request and session. Flask pushes both for a normal request: the request context first, and an application context along with it. Code that only needs current_app and g (a CLI command, a background task) can run with the application context alone, while code that reads request needs the full request context. In tests, app.test_request_context("/path") gives you both without sending anything.

The classic g pattern: a resource per request

The most common use of g plus a teardown hook is "open on first use, close at the end". You saw it with SQLite in Using sqlite3 with Flask:

Python
def get_db():
    if "db" not in g:
        g.db = connect()
    return g.db

@app.teardown_appcontext
def close_db(error):
    db = g.pop("db", None)
    if db is not None:
        db.close()

g.pop("db", None) removes the attribute if it exists and does nothing otherwise, so the teardown works for requests that never touched the database.

Signals

Hooks are functions you attach to one app. Signals are announcements Flask broadcasts, which any number of listeners can subscribe to without changing the app's behavior. They are built on the blinker library, which Flask installs for you. Useful built-in signals include request_started, request_finished, got_request_exception, template_rendered and message_flashed.

A listener receives the sender (the app) and keyword arguments, so always accept **extra. Use hooks to change behavior, and signals to observe it: logging, metrics and test assertions are the typical uses.

Python Listening to signals

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Passing app as the second argument to connect limits the listener to that app. Without it, the listener hears every Flask app in the process. You can also create your own signals with blinker.Namespace().signal("user-registered") and call .send(app, user=user) where it happens.

Custom CLI commands

Flask ships with the flask command (flask run, flask shell, flask routes). You can add your own commands to it with @app.cli.command(). They are written with the click library, run inside an application context, and are perfect for one-off jobs: creating database tables, seeding demo data, sending a report.

In a real project you would run them in a terminal, like this (read-only, because the browser has no terminal):

Terminal
flask --app myapp greet --name Ada
flask --app myapp seed

You do not need a terminal to test them. app.test_cli_runner() returns a Click runner that executes a command in-process and captures its output and exit code.

Python A command tested with test_cli_runner

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

A bad argument does not crash your test. Click prints a usage error and sets the exit code to 2, which is easy to assert on. Related commands can be grouped with AppGroup or a blueprint's cli attribute, which gives names like flask users create.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What must an after_request function do?

    Flask passes the response to each after_request function and uses whatever they return, so every one must return a response object.
  2. 2. A before_request function returns ('Maintenance', 503). What happens?

    Returning a non-None value from before_request short-circuits the request. The view never runs, but the response still passes through after_request and teardown.
  3. 3. Why is teardown_appcontext a good place to close a database connection stored on g?

    Teardown functions always run when the context is popped, whether the request succeeded or failed, so resources get released either way.
  4. 4. What is true about data stored on g?

    g is created fresh for every application context. Use the session for per-user data across requests.
  5. 5. How do you run a custom command in a test without a terminal?

    test_cli_runner returns a Click runner. invoke runs the command in-process and gives you .output and .exit_code.

Summary

  • before_request runs before the view and can short-circuit by returning a response; after_request receives and must return the response; both teardown hooks run at the end, even after errors.
  • current_app and g need an application context. Flask provides one per request and per CLI command; app.app_context() creates one by hand.
  • g is a per-context notepad. It resets for every request, so it is ideal for a database connection (open lazily, close in teardown_appcontext).
  • Blueprint hooks apply only to that blueprint unless you use the *_app_* variants.
  • Signals (request_started, request_finished, got_request_exception, template_rendered) let you observe Flask without changing it.
  • @app.cli.command() adds commands to the flask tool, and app.test_cli_runner() tests them in-process.

Next: Password Hashing, the first step toward safe user accounts.