← Back to Django, page 3

django-0056 · Easy fresher

What happens inside Django between receiving an HTTP request and sending the response?

The web server hands the request to Django through WSGI or ASGI. Django builds an HttpRequest, passes it down the MIDDLEWARE list, resolves the URL to a view with the URLconf, calls the view (which may use the ORM and templates), and returns an HttpResponse that travels back up through the middleware in reverse order before the server sends it.

Full answer

Steps for one request:

  1. The server (Gunicorn, Uvicorn, runserver) calls Django's WSGI or ASGI handler.
  2. The handler creates an HttpRequest with method, headers, GET, POST and body.
  3. Each middleware in MIDDLEWARE runs top to bottom (its code before get_response). Security, sessions, CSRF and authentication middleware attach data such as request.session and request.user.
  4. The URL resolver matches request.path_info against ROOT_URLCONF, and finds a view plus its arguments. No match raises Http404.
  5. process_view hooks of middleware run, then the view runs. The view reads data (ORM), makes decisions and returns an HttpResponse, JsonResponse, redirect or a TemplateResponse.
  6. Template rendering happens (lazily for TemplateResponse).
  7. The response goes back up through the middleware bottom to top (code after get_response), where headers, cookies and compression are added.
  8. The handler sends the response. Exceptions are converted into 404, 403, 500 responses by the handler or error views; process_exception hooks run first.

Order matters. SessionMiddleware must come before AuthenticationMiddleware, because the user is read from the session. A middleware that returns early (like a maintenance page) short-circuits everything below it.

Signals such as request_started and request_finished fire at the edges of this flow, and database connections are closed when the request ends.

python
import sys
import types

import django
from django.conf import settings

# Register a tiny in-memory "school" app so this example runs as one file
sys.modules["school"] = types.ModuleType("school")
sys.modules["school"].__file__ = __file__

settings.configure(
    SECRET_KEY="demo-only-key-not-for-production",
    ALLOWED_HOSTS=["testserver"],  # the host name used by Django's test client
    ROOT_URLCONF=__name__,
    MIDDLEWARE=["__main__.TraceOne", "__main__.TraceTwo"],
    INSTALLED_APPS=["django.contrib.contenttypes", "django.contrib.auth", "school"],
    DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
)
django.setup()

from django.http import HttpResponse
from django.test import Client
from django.urls import path

events = []


class TraceOne:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        events.append("one: before view")
        response = self.get_response(request)
        events.append("one: after view")
        return response


class TraceTwo:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        events.append("two: before view")
        response = self.get_response(request)
        events.append("two: after view")
        return response

    def process_view(self, request, view_func, view_args, view_kwargs):
        events.append(f"two: process_view -> {view_func.__name__}")


def hello(request):
    events.append("view runs")
    return HttpResponse("hello")


urlpatterns = [path("hello/", hello)]

r = Client().get("/hello/")
print(r.status_code, r.content)
print("\n".join(events))
events.clear()
print(Client().get("/missing/").status_code, events)

Standalone script. The first lines register a tiny in-memory app called school and an in-memory SQLite database so the file runs with `python file.py`. In a real project the settings live in settings.py and models live in an app's models.py. The middleware classes live in the same file, referenced through the __main__ module path. Output (ran twice with identical results; Python 3.13.5, Django 5.2.20, djangorestframework 3.18.3): 200 b'hello' one: before view two: before view two: process_view -> hello view runs two: after view one: after view 404 ['one: before view', 'two: before view', 'two: after view', 'one: after view']

Key points

  • Server calls WSGI or ASGI handler, which builds HttpRequest
  • Middleware runs in order down, then in reverse on the way back
  • URLconf resolves the view; no match gives 404
  • The view returns a response object
  • Middleware order is a dependency order

Common mistakes

  • Putting AuthenticationMiddleware before SessionMiddleware
  • Assuming the view is the only code that touches the request
  • Putting heavy work in middleware that runs on every request
  • Forgetting that exceptions are turned into responses by the handler

Follow-ups

  • What is the difference between process_view and the __call__ style?
  • Where does CSRF checking happen?
  • What changes in the flow under ASGI?

Tips

  • Walk through the steps in order
  • Mention reverse order for responses
  • Name one order dependency