Flask Request and Application Context Lifecycle
This state diagram illustrates the lifecycle of the AppContext in Flask, which now encompasses what was previously the RequestContext. The lifecycle begins with the creation of an AppContext instance, where the Storing Data During a Context with g object is initialized as a namespace for the context.
When push() is called, the context is attached to the current execution unit via a ContextVar (_cv_app), making the current_app and g proxies available. If the context contains request data (making it a "request context"), it transitions into a request-handling state where the Introduction to Sessions in Flask is opened and routing is performed.
The diagram follows the request through its dispatching phases: preprocessing, dispatching to the view function, and finalizing the response (where the session is saved). Finally, the pop() method triggers the teardown process, executing both request-specific and application-wide teardown handlers before resetting the global state.
Key design decisions discovered:
- Context Merger: Flask 3.2 merged
RequestContextintoAppContext. - Lazy Session Loading: The session is opened either during
push()for a request context or upon first access. - Nesting Support: A
_push_countattribute allows contexts to be pushed multiple times, with cleanup only occurring on the finalpop(). - Signal Integration: The lifecycle is punctuated by several signals (e.g.,
appcontext_pushed,request_tearing_down) that allow extensions to hook into the process.
Key Architectural Findings:
- AppContext and RequestContext are merged into a single class in Flask 3.2.
- The lifecycle is managed by push() and pop() methods which manipulate a ContextVar.
- The 'g' object is a namespace instance created during AppContext initialization.
- The 'session' is opened during the push of a request-enabled context and saved during response processing.
- Teardown is a two-stage process: first for the request (if present), then for the application context.
- A push count tracks nested context usage, ensuring cleanup only happens when the outermost context is popped.