Skip to main content

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:

  1. Context Management: A combined AppContext (which in Flask 3.2+ includes request-specific data) is created and pushed onto the context stack. This makes the request, session, and g globals available.
  2. Routing: During the context push, match_request is called to match the incoming URL against registered rules, determining the target endpoint and view arguments.
  3. Request Dispatching: full_dispatch_request handles the core logic, including:
    • Preprocessing: Executing before_request handlers.
    • Dispatching: Calling the actual Registering Routes and Handlers associated with the matched endpoint.
    • Finalization: Converting the view's return value into a proper Response object via make_response and running after_request handlers.
  4. Response Execution: The Response object itself is a WSGI application, which is called to send the status, headers, and body back to the server.
  5. Teardown: Finally, the context is popped, triggering teardown_request and teardown_appcontext handlers to clean up resources (like database connections).

Key Architectural Findings:

  • Flask 3.2+ has merged RequestContext into AppContext, simplifying the context stack management.
  • The wsgi_app method 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 Response object 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 a finally block.
Loading diagram...