Skip to main content

Flask AppContext Lifecycle States

This state diagram illustrates the lifecycle of the AppContext in Flask, which as of version 3.2, also encompasses the functionality previously handled by RequestContext.

The lifecycle begins with the creation of an AppContext instance, which can be either a pure application context or one initialized with request data (a "request context"). When push() is called, the context becomes active by being placed into a contextvars storage, making proxies like current_app and g available. If it's a request context, it further transitions into a state where the session is opened and routing is performed, followed by the request dispatching phase.

The dispatching phase itself consists of preprocessing, the actual view function execution, and finalization (response processing).

The lifecycle concludes with pop(). If the context was pushed multiple times (nested), it remains active until the final pop. The final pop triggers a sequence of teardown operations: first for the request (if present), including closing the request object, and then for the application context itself. Finally, the context is removed from the stack, and the appcontext_popped signal is emitted.

Key Architectural Findings:

  • In Flask 3.2+, RequestContext has been merged into AppContext. AppContext now handles both application and request-level state.
  • The context lifecycle is managed by push() and pop() methods which use contextvars to maintain a stack-like behavior.
  • A context is considered a 'request context' if it is initialized with a Request object; this triggers additional logic during push() (session loading, routing) and pop() (request teardown).
  • The _push_count attribute allows for nested context management, where cleanup only occurs when the outermost context is popped.
  • Teardown functions and signals (like appcontext_tearing_down and request_tearing_down) are executed in a specific order during the final pop().
Loading diagram...