Skip to main content

Flask AppContext and RequestContext Lifecycle

This state diagram illustrates the lifecycle of the AppContext (which now encompasses the functionality previously held by RequestContext in Flask 3.2+).

The lifecycle begins with the creation of an AppContext instance, either via app.app_context() for a pure application context or app.request_context(environ) for a request-aware context.

When push() is called, the context is bound to the current execution thread/task using a contextvars.ContextVar named _cv_app. If it's a request context, it automatically handles session opening and request matching (routing).

The Active state represents the period where the context is available via flask.globals proxies like current_app, g, request, and session. Flask supports nested pushes of the same context, tracked by a _push_count.

The Popping phase occurs when pop() is called. Cleanup only happens when the _push_count reaches zero. This cleanup involves calling teardown functions for both the request (if applicable) and the application context, closing the request, and finally resetting the global state.

Key signals are emitted throughout the lifecycle, allowing extensions to hook into these transitions.

Key Architectural Findings:

  • In Flask 3.2+, RequestContext has been merged into AppContext; they share the same underlying class and lifecycle logic.
  • The context lifecycle is managed by push() and pop() methods, which use contextvars to maintain state across async tasks and threads.
  • A _push_count attribute allows the same context instance to be pushed multiple times, with cleanup only occurring on the final pop.
  • Request-specific initialization (session opening, routing) is performed during the push() operation if request data is present.
  • Teardown functions (teardown_request and teardown_appcontext) are executed in reverse order of registration during the final pop().
  • The flask.globals proxies (current_app, g, request, session) are implemented as LocalProxy objects pointing to the active AppContext in the _cv_app ContextVar.
Loading diagram...