Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 77 ยท Getting Started

The Request and Response Cycle

Follow a request through WSGI or ASGI, middleware, the URL resolver and a view, and learn the HttpRequest and HttpResponse attributes you use every day.

Every page a Django site serves starts as an HTTP request and ends as an HTTP response. Between the two, Django runs a fixed series of steps. If you know the sequence, debugging gets easier: you can tell whether a problem lives in the server, in a middleware, in the URL configuration, in the view or in the template.

In this lesson you will follow one request from the web server to your code and back, then take the two central objects, HttpRequest and HttpResponse, apart attribute by attribute. All examples run live using Django's test client and RequestFactory, which exercise the same code path a real server does, without needing a network.

The journey of a request

Django is a request-response machine. A request arrives; exactly one response leaves. Here is the full path:

sequenceDiagram
    participant B as Browser
    participant S as Web server<br/>(WSGI or ASGI)
    participant M as Middleware stack
    participant R as URL resolver
    participant V as View
    B->>S: HTTP request
    S->>M: HttpRequest
    M->>R: request (after each middleware)
    R->>V: matched view + arguments
    V-->>M: HttpResponse
    M-->>S: response (in reverse order)
    S-->>B: HTTP response

The request goes down through the middleware to the view; the response comes back up through the same layers in reverse.

  1. The web server (Gunicorn or the development server for WSGI, Uvicorn or Daphne for ASGI) accepts the connection and parses the HTTP text into a standard Python interface.
  2. The handler (WSGIHandler or ASGIHandler, created in your project's wsgi.py or asgi.py) builds an HttpRequest object.
  3. Middleware wraps the rest of the pipeline. Each layer can inspect or change the request on the way in and the response on the way out.
  4. The URL resolver matches request.path_info against urlpatterns and finds the view and its arguments.
  5. The view does the real work and returns an HttpResponse.
  6. The response travels back through the middleware in reverse order, is converted into HTTP bytes by the handler and is sent to the browser.

WSGI versus ASGI

WSGI (Web Server Gateway Interface) is the classic synchronous standard: one request is handled by one worker at a time. ASGI is its asynchronous successor, which allows async views, WebSockets and long-lived connections. A new Django project ships both entry points. You pick one when you deploy; for ordinary sync views, WSGI is perfectly fine. The details are in Async Django and Deploying Django.

Middleware: the onion

Middleware are small components configured in the MIDDLEWARE setting. Think of an onion: the first middleware in the list is the outermost layer. On the way in, requests pass through layers from top to bottom; on the way out, responses pass through them from bottom to top. A layer can also short-circuit: if it returns a response without calling the next layer, the view never runs, which is how security and authentication middleware reject requests early.

The example below defines two tracing middleware that record when they see the request and the response, and then sends three requests: a normal page, a URL that does not exist, and a view that crashes.

Python Tracing a request through middleware

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.

Study the three traces:

  • Normal request: outer in, inner in, view, inner out, outer out. The onion in action.
  • Unknown URL: the resolver finds nothing, so the view never runs, but Django still produces a 404 response and it still travels back out through both layers. Middleware sees every response, including errors.
  • Crashing view: Django catches the exception and converts it into a 500 response before it reaches your middleware. That is why even the crash leaves a tidy "response out (500)" line. (raise_request_exception=False keeps the test client from re-raising the exception to your script.)

A middleware in this tutorial is a function that takes get_response and returns another function. You can also write it as a class, with hooks like process_view; both styles are covered in Middleware.

The URL resolver

After the middleware, Django hands the path to the resolver, which walks through urlpatterns from top to bottom and stops at the first match. The match gives it a view function plus any values captured from the URL (like the 5 in /orders/5/). If nothing matches, Django raises Http404. The next section of the tutorial is devoted to URL routing.

HttpRequest: what the view receives

The first argument of every view is an HttpRequest. It is a snapshot of everything the client sent. Django parses the raw HTTP into Python objects so you rarely touch bytes.

Attribute Meaning
request.method "GET", "POST", and so on (always uppercase).
request.path The URL path without the query string, such as /orders/5/.
request.GET The query string as a QueryDict (a dictionary that can hold several values per key).
request.POST Form data from a POST body, also a QueryDict.
request.FILES Uploaded files.
request.body The raw body as bytes (use this for JSON).
request.headers Case-insensitive access to HTTP headers.
request.META The low-level dictionary of server and header values.
request.COOKIES Cookies sent by the browser.
request.user The logged-in user (added by the authentication middleware).
request.session The session (added by the session middleware).

Methods worth knowing: get_host(), get_full_path(), build_absolute_uri(), is_secure(), and request.GET.getlist("tag") for repeated keys.

Notice that request.user and request.session do not exist by themselves. They are attached by middleware, which is one more reason the middleware order matters. Query Strings, Forms and Request Data covers these attributes in depth.

HttpResponse: what the view returns

A view must return an HttpResponse (or a subclass), or raise an exception such as Http404. A response has:

  • status_code (and reason_phrase, derived from it),
  • content, a bytes body,
  • headers, a dictionary-like set of HTTP headers (response["X-Name"] = "value" also works),
  • cookies, set with set_cookie() and removed with delete_cookie().

Common subclasses are JsonResponse, HttpResponseRedirect (302), HttpResponsePermanentRedirect (301), HttpResponseNotFound (404), HttpResponseBadRequest (400) and StreamingHttpResponse for large bodies. Shortcuts like render() and redirect() build these for you, as shown in Function-Based Views.

Python Taking HttpRequest and HttpResponse apart

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.

RequestFactory creates an HttpRequest directly and does not run middleware or URL resolution, which makes it ideal for testing a single view in isolation or exploring request attributes. Client, which you used in the previous example, goes through the full stack including middleware. Notice how the header X-Request-Id is available as request.headers["X-Request-Id"] but is stored in request.META as HTTP_X_REQUEST_ID.

Two objects, one rule: the request is what the client said, the response is what the server answers. A view should treat the request as read-only input and put everything it wants to send into the response. Anything that needs to be shared across requests belongs in the database, the session or a cache, not in module-level variables.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Middleware A is listed before middleware B in MIDDLEWARE. In which order does the response pass through them?

    Requests go down the list (A, then B, then the view). Responses travel back in reverse order: B first, then A.
  2. 2. What does a view receive as its first argument?

    Django passes an HttpRequest instance, followed by any values captured from the URL.
  3. 3. Which attribute holds uploaded files?

    request.FILES contains uploaded files. request.POST only holds ordinary form fields.
  4. 4. How does RequestFactory differ from the test Client?

    RequestFactory returns a bare HttpRequest that you pass straight to a view. The Client runs the whole request cycle including middleware and URL routing.
  5. 5. A view raises an unhandled exception. What reaches the middleware on the way out?

    Django catches the exception and turns it into an error response, so the middleware still sees a normal response object.

Summary

  • A request goes web server, WSGI or ASGI handler, middleware, URL resolver, view; the response returns through the middleware in reverse.
  • Middleware wraps the whole pipeline and can short-circuit; every response, including 404 and 500, passes through it.
  • The resolver walks urlpatterns top to bottom, and the first match wins.
  • HttpRequest exposes method, path, GET, POST, FILES, body, headers, META, COOKIES, plus user and session added by middleware.
  • HttpResponse has a status code, a body, headers and cookies; subclasses like JsonResponse cover common cases.
  • RequestFactory tests one view in isolation; Client runs the full stack.

Next lesson: URL Routing.