Request-Response Lifecycle
This sequence diagram illustrates the lifecycle of a single HTTP request within the Flask framework, following the WSGI standard.
The process begins when the WSGI Server invokes the Flask application's __call__ method. This delegates to wsgi_app, which orchestrates the entire lifecycle.
Key stages include:
- Context Management: A combined
AppContext(which in Flask 3.2+ includes request-specific data) is created and pushed onto the context stack. This makes therequest,session, andgglobals available. - Routing: During the context push,
match_requestis called to match the incoming URL against registered rules, determining the target endpoint and view arguments. - Request Dispatching:
full_dispatch_requesthandles the core logic, including:- Preprocessing: Executing
before_requesthandlers. - Dispatching: Calling the actual Registering Routes and Handlers associated with the matched endpoint.
- Finalization: Converting the view's return value into a proper
Responseobject viamake_responseand runningafter_requesthandlers.
- Preprocessing: Executing
- Response Execution: The
Responseobject itself is a WSGI application, which is called to send the status, headers, and body back to the server. - Teardown: Finally, the context is popped, triggering
teardown_requestandteardown_appcontexthandlers to clean up resources (like database connections).
Key Architectural Findings:
- Flask 3.2+ has merged
RequestContextintoAppContext, simplifying the context stack management. - The
wsgi_appmethod is the primary orchestrator, ensuring that contexts are popped even if exceptions occur during dispatch. - Routing (URL matching) happens during the
AppContext.push()phase if request data is present. - The
Responseobject is itself a WSGI application that Flask calls to finalize the communication with the WSGI server. - Teardown functions are guaranteed to run at the end of the request lifecycle via the
ctx.pop()call in afinallyblock.
Loading diagram...