Skip to main content

Request-Response Lifecycle Flow

This sequence diagram illustrates the lifecycle of a request in Flask, from the moment it is received by the WSGI server to the point where a response is returned.

The process begins with the WSGI server calling the Flask application's __call__ method, which delegates to wsgi_app. A new AppContext (which in modern Flask versions like this one, has merged with the former RequestContext) is created to manage the request's state.

During the context's push phase, the MapAdapter (from Werkzeug) is used to match the incoming request URL against the application's routing rules. Once matched, the request is dispatched through full_dispatch_request, which handles preprocessing (like before_request hooks), the actual view function execution, and post-processing (like after_request hooks).

Finally, the return value from the view is converted into a proper Response object, which is then called as a WSGI application to send the data back to the server. The context is then popped, triggering teardown functions.

Key Architectural Findings:

  • Flask 3.2+ has merged RequestContext into AppContext, simplifying the context stack.
  • The request-response lifecycle is managed primarily within the wsgi_app method of the Flask class.
  • Routing is performed during the context push phase via AppContext.match_request using Werkzeug's MapAdapter.
  • The full_dispatch_request method orchestrates preprocessing, dispatching to view functions, and finalizing the response.
  • Context management now uses Python's contextvars (via _cv_app) instead of the legacy _request_ctx_stack.
Loading diagram...