Request and Application Contexts

Request and Application Contexts in Flask: Picture a busy passport office on a weekday morning.

The Analogy: The Walk-In Passport Office Counter

Picture a busy passport office on a weekday morning. The branch has opened for the day: the shutters are up, the master rulebook sits on the supervisor's desk, the shared reference shelves are stocked, and the fee schedule is pinned to the wall. None of that belongs to any one visitor -- it is the state of the office itself, established once when the branch opened and unchanged as person after person is served. When a clerk needs to know the current fee or which forms are accepted, they consult these office-wide fixtures. This is the backdrop against which every individual transaction happens.

Now an applicant steps up to window three. The moment they do, a service transaction begins: the clerk pulls the applicant's file, and for as long as that person stands at the window, words like "the current applicant", "their form", and "the photo they handed over" all point unambiguously at this one visitor. The clerk never has to ask "which applicant?" -- being at the window IS the answer. When this person finishes and walks away, those words go hollow again: if the clerk, mid-coffee-break with nobody at the window, mutters "what is the current applicant's date of birth?", the question is meaningless. There is no current applicant to point at.

While serving someone, the clerk clips a small scratch slip to the file -- a running tally of how many records they have pulled, a note that the fee has been collected, a reminder to double-check a spelling. That slip exists only for this one transaction. The instant the applicant leaves, the slip is torn off and shredded; the next person gets a fresh blank slip. Crucially, the slip is never confused between windows: window three's slip stays with window three's applicant, and window four keeps its own, even though both clerks work from the same rulebook and the same fee schedule at the same time.

The failure mode is what happens if the office tries to economise with a single clipboard bolted to the wall, labelled "CURRENT APPLICANT" and shared by every window. The moment two clerks serve two people at once, applicant A's date of birth overwrites applicant B's on the shared board, and B's passport is issued with A's details. The office avoids this precisely by giving every window its own slip rather than one shared board. Flask draws exactly this line: the office-that-is-open is the application context (holding app-wide config and resources), the person-at-the-window is the request context (holding this one request's data), the scratch slip is the g object, and the shared wall clipboard is the module-level global that quietly corrupts one request with another's data under concurrency.


Syntax or Core Structure

Flask exposes the "current transaction" through a handful of context globals that you import once and use anywhere in the call stack, without threading them through every function argument. The most important is request, which describes the incoming HTTP call: its method, path, query-string arguments, parsed JSON body, and headers. Because it is a proxy for "the request being handled right now," you never construct it yourself -- Flask binds it for the duration of each view and unbinds it when the view returns.

from flask import Flask, request, jsonify

app = Flask(__name__)


@app.post("/echo")
def echo():
    return jsonify(
        method=request.method,
        path=request.path,
        arg=request.args.get("tool"),
        json_name=request.json.get("name"),
        ua=request.headers.get("User-Agent"),
    )


client = app.test_client()
resp = client.post(
    "/echo?tool=tools",
    json={"name": "Mallet"},
    headers={"User-Agent": "probe/1.0"},
)
print(resp.status_code)
print(resp.get_json())

Output:

200
{'arg': 'tools', 'json_name': 'Mallet', 'method': 'POST', 'path': '/echo', 'ua': 'probe/1.0'}

Four different slices of the incoming request are read through one object. request.method is the verb the router already dispatched on; request.args is a dict-like view of the query string, where .get("tool") returns None rather than raising if the key is absent; request.json parses the body as JSON on demand; and request.headers is a case-insensitive mapping, so "User-Agent" and "user-agent" reach the same value. Notice that jsonify sorts keys alphabetically, which is why the printed dict reads arg, json_name, method, path, ua rather than the order the code lists them. Reaching for .get() on both the query args and the JSON body is the defensive default: a caller who omits tool or sends no name yields None, not a 400-turned-500 crash.


Technical Depth: Two Contexts, Four Proxies, One Rule

Flask actually maintains two stacked contexts, not one, and the four globals you reach for each belong to a specific layer. The application context represents "this app is active on this thread" and carries current_app and g. The request context represents "an HTTP request is being handled" and carries request and session. Whenever a request context is pushed, an application context is pushed underneath it automatically, which is why g is available inside every view even though it technically lives on the application layer.

The four context globals

ProxyContext requiredWhat it holdsBound during
current_appApplicationthe active app object and its configa request, or an explicit app_context()
gApplicationper-context scratch storage, one per requesta request, or an explicit app_context()
requestRequestthis call's method, args, body, headersthe handling of one HTTP request
sessionRequestthe signed, per-user cookie payloadthe handling of one HTTP request

Each of these is a proxy, not the object itself. Importing request once at module load does not freeze it to a single call; the name resolves, every time you touch an attribute, to whichever request is active on the current thread. That indirection is what lets you write from flask import request at the top of ten modules and have all of them see the correct per-request data with no argument passing -- and it is also why touching one of these names when no context is active raises immediately instead of handing you stale data.


Touching request data with nobody at the window

If you read request when no request is being handled -- from a script, a background thread, or a REPL -- Flask does not return an empty object or None. It raises a RuntimeError, the exact equivalent of the clerk asking for "the current applicant" with the window empty. To exercise request code off the request path (in a test, say), you push a request context by hand with test_request_context.

from flask import Flask, request

app = Flask(__name__)

print("outside any context:")
try:
    print("  request.path =", request.path)
except RuntimeError as e:
    print("  RuntimeError:", str(e).splitlines()[0])

print("inside test_request_context:")
with app.test_request_context("/whereami?x=1"):
    print("  request.path =", request.path)
    print("  request.args['x'] =", request.args["x"])

Output:

outside any context:
  RuntimeError: Working outside of request context.
inside test_request_context:
  request.path = /whereami
  request.args['x'] = 1

The bare request.path blows up because no window is open; the same line inside the with block succeeds because test_request_context pushed a synthetic request onto the stack for the duration of the block. This is not a testing-only trick: app.app_context() and app.test_request_context() are the supported way to run request- or app-dependent code from CLI commands, scheduled jobs, and shell sessions.


current_app: reaching the app without importing it

Modules that define blueprints or helpers must not import the app object directly -- that creates circular imports and hard-codes a single app. Instead they read current_app, the proxy that resolves to whichever app is active. Like request, it is unbound outside a context, so off-request code wraps itself in app_context().

from flask import Flask, current_app

app = Flask(__name__)
app.config["RATE_LIMIT"] = 100

try:
    print(current_app.config["RATE_LIMIT"])
except RuntimeError as e:
    print("outside app context:", str(e).splitlines()[0])

with app.app_context():
    limit = current_app.config["RATE_LIMIT"]
    print("inside app context: RATE_LIMIT =", limit)

Output:

outside app context: Working outside of application context.
inside app context: RATE_LIMIT = 100

Note the message differs from the request-context one: "application context" versus "request context." Reading that word tells you which layer you forgot to push. Inside app_context(), current_app resolves and its config is available, which is how a nightly report job or a flask CLI command reaches the same configuration your views use.

g: a fresh scratch slip per request

The g object is per-request scratch storage. It is the canonical place to cache a resource -- a database handle, the current user, a computed value -- so that repeated lookups within one request reuse it, while the next request starts clean.

from flask import Flask, g, jsonify

app = Flask(__name__)
_counter = {"n": 0}


def get_db():
    if "conn_id" not in g:
        _counter["n"] += 1
        g.conn_id = _counter["n"]
    return g.conn_id


@app.get("/who")
def who():
    first = get_db()
    second = get_db()
    return jsonify(first=first, second=second)


client = app.test_client()
print("req1:", client.get("/who").get_json())
print("req2:", client.get("/who").get_json())
print("total connections created:", _counter["n"])

Output:

req1: {'first': 1, 'second': 1}
req2: {'first': 2, 'second': 2}
total connections created: 2

Within a single request get_db is called twice but the connection is created once -- first and second match because the second call finds conn_id already on g. The next request gets a blank g, so it builds its own connection, and the global tally lands at two connections for two requests rather than four for four calls. This is the correct pattern for request-scoped resources; the anti-pattern is caching that handle in a module-level variable, which would share one connection across concurrent requests and, worse, keep it alive forever.


Real World Example: A Per-Request Unit of Work

Almost every real API wants the same lifecycle: when a request arrives, open one database connection (or begin one transaction), let every handler and helper in that request share it, and close it exactly once when the request ends -- succeed or fail. Flask models this with two hooks, before_request and teardown_request, and stores the shared resource on g so that any function in the call stack can reach it without being handed it explicitly. The example below stands in for that pattern with a query counter: before_request opens the "unit of work," helpers increment it through g, and teardown_request closes it.

from flask import Flask, g, request, jsonify

app = Flask(__name__)
log = []


@app.before_request
def open_unit_of_work():
    g.queries = 0
    log.append(f"begin {request.path}")


def run_query(sql):
    g.queries += 1
    return f"[{g.queries}] {sql}"


@app.get("/orders/<int:oid>")
def order(oid):
    run_query(f"SELECT * FROM orders WHERE id={oid}")
    run_query(f"SELECT * FROM items WHERE order_id={oid}")
    return jsonify(order=oid, queries=g.queries)


@app.teardown_request
def close_unit_of_work(exc):
    log.append(f"end queries={g.get('queries', 0)}")


client = app.test_client()
print(client.get("/orders/7").get_json())
print(client.get("/orders/8").get_json())
print("log:", log)

Output:

{'order': 7, 'queries': 2}
{'order': 8, 'queries': 2}
log: ['begin /orders/7', 'end queries=2', 'begin /orders/8', 'end queries=2']

The mechanics read straight down the request lifecycle. open_unit_of_work runs first for every request, planting a fresh g.queries = 0 -- a new scratch slip for this window -- and recording where the request began. The view calls run_query twice; because both calls mutate the same g.queries, the second sees the first's increment, and the handler returns a count of two. When the view returns, close_unit_of_work fires and reads the final tally off g before the context is torn down and the slip is shredded.

The output confirms the isolation the analogy promised. Both /orders/7 and /orders/8 report exactly two queries, not two-then-four: the counter did not leak from the first request into the second, because g was rebuilt at the start of each. The interleaving in log -- begin, end, begin, end -- shows each unit of work fully opening and closing before the next request starts, which is precisely the guarantee you want from a per-request connection: no request ever sees another's half-open transaction.

Reached for as a template, this is the standard Flask persistence pattern, and swapping the counter for a real sqlite3 or SQLAlchemy connection changes almost nothing in the shape of the code. The connection would be created lazily in a get_db helper (as in the g-caching example above), reused across every query in the request, and closed in teardown_request. Storing it on g rather than a module global is what keeps concurrent requests from sharing one connection -- the shared-wall-clipboard bug the analogy warned about.

The genuine design flaw is in close_unit_of_work: it accepts the exc argument that Flask passes -- None on success, the exception object when the view raised -- and then completely ignores it. For a mere query counter that is harmless, but the instant this becomes a real transaction the flaw bites: teardown fires identically whether the request succeeded or blew up halfway through a multi-statement write, so the code has no way to commit on success and roll back on failure. A partially-applied transaction would be torn down exactly like a clean one, silently leaving the database in a half-written state. A correct unit of work must branch on exc: commit when it is None, roll back otherwise. The counter version hides this because it has nothing to roll back -- which is exactly how this class of bug slips into production untested.


Common Mistakes

  1. Storing per-request state in a module-level variable instead of g. A global current_user or db_conn at module scope is the shared wall clipboard: under any real concurrency, one request overwrites another's value. Request-scoped data belongs on g, which is isolated per request.
  1. Importing the app object directly in blueprints or helpers. from myapp import app hard-codes one app and invites circular imports. Reach the running app through current_app instead, so the code works under the app factory pattern and in tests.
  1. Touching request from a background thread or CLI command. request is bound only while an HTTP request is being handled; a thread you spawned has no request context and will raise RuntimeError: Working outside of request context. Capture the values you need before spawning.
  1. Expecting g to persist between requests. g is reset for every request; it is not a cache that survives across calls. Using it to memoise something for the whole process silently loses the value on the next request.
  1. Calling request.json on a request that is not JSON. In modern Flask this raises a 415 rather than returning None. Use request.get_json(silent=True) when the body might be absent or non-JSON, and check for None.
  1. Indexing request.args["key"] for optional parameters. Bracket access raises a 400 BadRequestKeyError when the key is missing. Use request.args.get("key") (optionally with a default) unless the parameter is genuinely required.
  1. Ignoring the exc argument in teardown_request. Teardown runs on both success and failure; a teardown that does not branch on exc cannot commit on success and roll back on error, leaving transactional resources in a half-written state.
  1. Doing expensive work in before_request for every route. A hook that hits the database on every request also runs for health checks and static files. Scope costly hooks to a blueprint, or guard them by inspecting request.endpoint.
  1. Confusing the application context with the request context. Pushing app_context() does not give you request; pushing a request context is what binds request data. Read the RuntimeError message -- "application" versus "request" -- to see which layer you actually need.

Best Practices

  • Create request-scoped resources lazily on g and release them in teardown_request. A get_db() that caches on g gives every helper in the request one shared connection, opened only if used and closed exactly once.
  • Reach the app through current_app, never a direct import. This keeps blueprints and utilities decoupled from a single app instance and compatible with the application factory pattern.
  • Be forgiving with input: request.get_json(silent=True) and request.args.get(...). Missing or malformed input should yield None you can validate, not an unhandled 400 or 415.
  • Branch on exc in teardown to commit or roll back. Commit the unit of work when exc is None and roll it back otherwise, so a failed request never leaves partial writes behind.
  • Run off-request code inside an explicit context. Wrap CLI commands, jobs, and scripts in app.app_context(), and use test_request_context() when you need request data, rather than fabricating a fake request.
  • Keep before_request hooks cheap and scoped. Attach heavy hooks to the blueprint that needs them, or short-circuit for static and health endpoints, so they do not tax every route.
  • Treat context globals as live proxies, not values to stash. Do not assign request to a long-lived variable or hand it to another thread; read what you need from it while the context is active.
  • Exercise context code with test_client and test_request_context. These push real contexts in-process, so tests behave exactly like production request handling without binding a socket.

Practice Exercises

  1. Per-request id. Write a before_request hook that stores a random request id on g, and an after_request hook that echoes it back in an X-Request-Id response header. Verify with test_client that two requests get two different ids.
  1. Cached current user. Implement get_current_user() that caches its result on g, and prove with a counter that calling it twice within one request performs the underlying lookup only once, while a second request performs it again.
  1. Correct unit of work. Convert the query-counter example into a real sqlite3 connection opened in before_request and closed in teardown_request, committing when exc is None and rolling back otherwise. Demonstrate both a successful request and one that raises mid-write.
  1. Off-request access. Write a script with no running server that uses app.app_context() to read a value from current_app.config, then uses app.test_request_context("/?q=hi") to call a view that reads request.args, printing both results.