Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 72 ยท Getting Started

How a Request Flows Through Flask

Follow one request through Flask: the WSGI environ, URL matching, the app and request contexts, hooks and the response object. Runnable examples included.

A Flask app looks simple from the outside: a URL goes in, a page comes out. Understanding what happens in between makes everything else easier to learn, from request and session to error handlers and testing. In this lesson you follow one request from the moment the server hands it over until the response goes back.

You do not need to memorize the internals. The goal is a mental picture you can use when something surprising happens, such as "Working outside of request context" or a hook that runs at a different time than expected.

The journey of a request

sequenceDiagram
    participant S as WSGI server
    participant F as Flask app
    participant V as Your view
    S->>F: environ, start_response
    F->>F: push app + request context
    F->>F: match URL to a route
    F->>F: before_request hooks
    F->>V: call the view
    V-->>F: return value
    F->>F: make the response, after_request hooks
    F->>F: pop contexts, teardown hooks
    F-->>S: status, headers, body

Every request goes through the same stages; your view is only one step in the middle.

The server calls the Flask object with two arguments, environ and start_response, exactly as in the WSGI example. Flask builds a Request object from environ, makes it available through the global name request, finds the matching view, calls it and converts whatever it returns into a Response object.

The WSGI environ

environ is a plain dictionary. Its keys follow the old CGI naming: REQUEST_METHOD, PATH_INFO, QUERY_STRING, wsgi.input for the body and HTTP_* keys for headers. You rarely read it directly, but it is useful to see once. Werkzeug can build one for you, and because the Flask app is a WSGI callable you can feed it by hand:

Python Calling the app like a server does

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

That is the whole contract. The server (Gunicorn, Waitress, or Flask's development server) does this for every connection; the test client in the rest of this course does the same with a nicer interface. This is why testing with the test client is realistic: it goes through the same code path as a real request, only without a network.

Two contexts: application and request

Inside a view you can write request.args or current_app.config without passing anything in. These names are context-local proxies: they point at the objects that belong to the request being handled right now, even if many requests are handled at the same time.

Flask maintains two contexts:

  • The application context gives access to current_app and g, a scratch object for data you share during one request (database connections, for example).
  • The request context gives access to request and session.

Flask pushes both when a request starts and pops them when it ends. Outside of a request they do not exist, and Flask raises a RuntimeError if you touch them. The test helpers app.app_context() and app.test_request_context() let you create contexts by hand:

Python Contexts and current_app

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice that opening a request context also gives you the app context. The reverse is not true: an app context alone has no request. The g object lives in the app context, so it starts empty again in the next request. Contexts are the reason Flask code can read as request.form["email"] instead of passing a request parameter through every function.

Note: Older tutorials talk about "request-local" and "thread-local" storage. Modern Flask uses Python's contextvars, which also work correctly with async code, but your code looks the same: you import the proxies and use them inside a request.

Hooks along the way

Flask lets you run your own functions at fixed stages of the journey:

  • before_request: runs before the view. If it returns a value, that value becomes the response and the view is skipped.
  • after_request: receives the response and must return a response; use it to add headers.
  • teardown_request: runs when the context is popped, even if an error happened.

The Hooks lesson goes deeper. A quick demonstration shows the order in which things happen:

Python The order of hooks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Look at the second list: for an unknown URL the view never runs, but before_request, after_request and teardown_request still do, because the 404 is itself turned into a response that travels through the same pipeline.

The response object

Whatever your view returns, Flask turns it into a Response. It has a status code, headers and a body, plus helpers for cookies. You can build one explicitly with make_response, which is handy when you want to modify it before returning:

Python Building and inspecting a response

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The development server (read-only)

When you run flask run, Flask starts Werkzeug's built-in development server. It speaks HTTP, calls your app through WSGI and offers a reloader and a debugger, which is perfect while coding.

Terminal
flask --app app run --debug

It is not meant for production: it handles requests poorly under load and its debugger allows running code in the browser. For a real site you put a production WSGI server in front of your app, as the Deployment lesson shows. Because the app only ever sees environ, nothing in your code changes between the two.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does a WSGI server pass to the Flask application for each request?

    The server calls the app with the environ dictionary describing the request and a start_response callable used to report status and headers.
  2. 2. What is current_app in a Flask view?

    current_app is a context-local proxy that points to the application whose context is active, so code can reach the app without importing it.
  3. 3. What happens if you read request.path outside any request?

    The request proxy only works while a request context is active; otherwise Flask raises a RuntimeError.
  4. 4. Which hook receives the response and must return a response?

    after_request functions get the response object and must return it (or a replacement), which makes them a good place to add headers.
  5. 5. Why is it fine to test with app.test_client() instead of a real server?

    The test client builds an environ and calls the app like a server would, so routing, hooks and error handling all run normally.

Summary

  • A WSGI server calls the Flask app with environ and start_response; Flask builds a Request and eventually a Response.
  • Flask pushes an application context (current_app, g) and a request context (request, session) around each request, then pops them.
  • app.app_context() and app.test_request_context() create contexts by hand for experiments and tests.
  • before_request, after_request and teardown_request run at fixed points around the view, including for 404 responses.
  • make_response gives you a response object you can change; the dev server is for development only.

Next: Project Layout and the flask Command, where we organize files and meet the command-line tool.