Skip to main content

Flask Request-Response Lifecycle

This sequence diagram traces the lifecycle of an HTTP request in Flask, from the moment it is received by the WSGI server to the final response and context teardown.

Key architectural highlights:

  • Context Management: Flask uses a unified AppContext (which merged with RequestContext in version 3.2) to manage request-local state. The context is pushed before dispatching and popped after the response is sent.
  • Request Dispatching: The full_dispatch_request method orchestrates the high-level flow, including preprocessing (before-request hooks), the actual dispatch to the view, and finalization (after-request hooks and response conversion).
  • Session Handling: The SessionInterface is integrated into the context lifecycle, with sessions being opened during context push and saved during response processing.
  • Async Support: Flask uses ensure_sync to wrap view functions, allowing it to handle both synchronous and asynchronous views (via asgiref) within a standard WSGI environment.
  • WSGI Compliance: The Flask object itself is a WSGI application, and the Response object is also a WSGI application that is called to start the response transmission.

Key Architectural Findings:

  • Flask 3.2+ has merged RequestContext into AppContext, simplifying the context stack.
  • The wsgi_app method is the internal entry point that allows middleware to wrap the application.
  • URL matching and session opening are triggered during the AppContext.push() call.
  • The full_dispatch_request method handles the transition from raw view return values to finalized Response objects.
  • Teardown handlers are executed during AppContext.pop(), ensuring resources are cleaned up even if an error occurred.
Loading diagram...