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+,
RequestContexthas been merged intoAppContext.AppContextnow handles both application and request-level state. - The context lifecycle is managed by
push()andpop()methods which usecontextvarsto maintain a stack-like behavior. - A context is considered a 'request context' if it is initialized with a
Requestobject; this triggers additional logic duringpush()(session loading, routing) andpop()(request teardown). - The
_push_countattribute allows for nested context management, where cleanup only occurs when the outermost context is popped. - Teardown functions and signals (like
appcontext_tearing_downandrequest_tearing_down) are executed in a specific order during the finalpop().