Skip to main content

Application and Request Contexts

If you try to access request.args or current_app.config in a standalone script or a test fixture, Flask raises a RuntimeError because no context is active. Flask uses contexts to make certain objects globally accessible within a specific scope without requiring them to be passed between every function.

The Unified Context

As of Flask 3.2, the application and request contexts are managed by a single class: AppContext (found in src/flask/ctx.py). This class tracks the state for the active application, the current request, the user session, and the g object.

A context is referred to as a "request context" if it contains request information, and an "app context" if it does not. Flask handles this automatically during a standard request cycle in Flask.wsgi_app, but you must manage it manually when working outside of a view function.

Application Context

The application context makes the current_app and g proxies available. You typically need this when running database migrations, CLI commands, or setup tasks that require access to the application's configuration.

To manually push an application context, use the app.app_context() method in a with block:

from flask import Flask, current_app

app = Flask(__name__)

with app.app_context():
# current_app is now available
print(current_app.name)

Internally, app.app_context() returns an AppContext instance. When the with block begins, it calls AppContext.push(), which sets a contextvars.Token in _cv_app (defined in src/flask/globals.py). This makes the application instance available to the current_app proxy.

Request Context

The request context extends the application context by adding request and session data. This is essential for testing view functions that rely on request headers, arguments, or form data.

Use app.test_request_context() to simulate a request environment:

with app.test_request_context("/?name=World", method="GET"):
from flask import request
assert request.args["name"] == "World"

This method uses Werkzeug's EnvironBuilder to create a WSGI environment and then initializes an AppContext with that environment via AppContext.from_environ.

Context Proxies

Flask provides four primary proxies that point to the active context's data. These are defined in src/flask/globals.py:

  • current_app: Points to the Flask application instance handling the current context.
  • request: Points to the Request object. Accessing this outside a request context raises a RuntimeError.
  • session: Points to the user session. In Flask 3.2+, the session is loaded lazily via AppContext._get_session() only when first accessed.
  • g: An instance of _AppCtxGlobals (from src/flask/ctx.py). It is a temporary storage namespace for the duration of the context.

Lifecycle and Teardown

When a context is popped (at the end of a with block or after a request is finished), Flask executes teardown functions. These are registered using decorators like @app.teardown_appcontext.

The AppContext.pop() method in src/flask/ctx.py ensures that cleanup happens in the correct order:

  1. It calls app.do_teardown_request() if request data was present.
  2. It calls app.do_teardown_appcontext().
  3. It resets the contextvars token to restore the previous state.

If you have nested context pushes, the teardown functions only run when the outermost context is popped, tracked by AppContext._push_count.

Background Tasks

If you start a background thread or task, the context is not automatically shared. To access request or session in a separate thread, use the copy_current_request_context decorator:

from flask import copy_current_request_context
import threading

@app.route("/")
def index():
@copy_current_request_context
def background_task():
# This function now has access to the original request
print(request.path)

threading.Thread(target=background_task).start()
return "Task started"

This decorator captures the active AppContext and ensures that ctx.copy().push() is called inside the wrapper when the task executes, providing a safe, independent copy of the context data.