Django Django

How does Django middleware wrap a request?

Dima Ноя 15, 2026

Short Answer

Each middleware is a factory called once at startup with the next thing in the chain, returning a callable that runs once per request. That callable does its work, calls get_response(request) to hand control inward, and does more work with the response on the way back — so the chain is an onion, not a queue. MIDDLEWARE is read top to bottom on the way in and bottom to top on the way out, with the view at the centre. A middleware that returns a response without calling get_response short-circuits everything inside it, including the view and URL resolution.


How It Works

The plain form is two nested functions:

def audit(get_response):
    def middleware(request):
        return get_response(request)
    return middleware


The outer function runs once, when Django builds the chain. It receives get_response — the next middleware inward, or the view handler at the innermost layer — and returns the callable that will handle every request. Anything expensive you set up belongs in the outer function; anything per-request belongs in the inner one.

The chain is assembled in reverse. Django starts with the view handler and wraps it in the last MIDDLEWARE entry, wraps that in the second-to-last, and so on, so the first entry ends up outermost. That single fact produces the ordering everyone memorises: on the way in, entries run top to bottom; on the way out, bottom to top. Code before get_response(request) is the request phase, code after it is the response phase, and they belong to the same function.

Because the outermost layers run before anything inner, middleware sits in front of URL resolution. A middleware can answer a request for a path that has no route at all — it never gets far enough for the resolver to raise a 404. This is what makes authentication, rate limiting, and blocklists natural middleware jobs: they decide before the routing layer is consulted.

Short-circuiting is just returning without calling get_response. Everything inward — remaining middleware, resolution, the view — is skipped, while everything outward still gets its response phase, because those layers are already mid-call waiting for a return value.

A middleware can also be a class with __init__(self, get_response) and __call__(self, request), which is the same shape with the factory expressed as a constructor. The class form is required for the optional hooks Django looks for by name: process_view, process_exception, and process_template_response. These are not part of the onion — Django calls them at specific points, and process_exception in particular fires when the view raises, letting you convert the exception into a response.


Seeing It Run

These steps share a fixture. Create bootstrap.py, routes.py, and mw.py as shown in the first step, then replace main.py for each later step. Each main.py swaps the MIDDLEWARE list with override_settings so the three configurations run from one fixture; in a project that list lives in settings.py. Run with:

python3 main.py

The onion, in and out

Three identical tracing middlewares, so the only thing the output shows is order.

# bootstrap.py
import django
from django.conf import settings

settings.configure(
    DEBUG=False,
    SECRET_KEY="not-a-secret",
    ALLOWED_HOSTS=["*"],
    ROOT_URLCONF="routes",
    MIDDLEWARE=[],
)
django.setup()


# routes.py
from django.http import HttpResponse
from django.urls import path


def dock_board(request):
    print("    view runs")
    return HttpResponse("board")


def carrier_feed(request):
    raise ValueError("carrier feed unavailable")


urlpatterns = [
    path("docks/", dock_board, name="dock-board"),
    path("feed/", carrier_feed, name="carrier-feed"),
]


# mw.py
from django.http import HttpResponse


def trace(label):
    def factory(get_response):
        def middleware(request):
            print(f"  -> {label}")
            response = get_response(request)
            print(f"  <- {label}")
            return response

        return middleware

    return factory


outer = trace("outer")
middle = trace("middle")
inner = trace("inner")


def blocklist(get_response):
    def middleware(request):
        print("  -> blocklist")
        if request.path.startswith("/restricted"):
            print("  <- blocklist (short-circuited)")
            return HttpResponse("blocked", status=403)
        response = get_response(request)
        print("  <- blocklist")
        return response

    return middleware


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

    def __call__(self, request):
        print("  -> audit")
        response = self.get_response(request)
        print("  <- audit, status", response.status_code)
        return response

    def process_exception(self, request, exception):
        print("  process_exception saw:", type(exception).__name__)
        return HttpResponse("degraded", status=503)


# main.py
import bootstrap  # noqa: F401
from django.test import Client, override_settings

with override_settings(MIDDLEWARE=["mw.outer", "mw.middle", "mw.inner"]):
    response = Client().get("/docks/")

print("status:", response.status_code)


  -> outer
  -> middle
  -> inner
    view runs
  <- inner
  <- middle
  <- outer
status: 200


The arrows are a mirror image around the view. outer is first in MIDDLEWARE and therefore outermost, so it speaks first and last; inner is last in the list and sits closest to the view. Both halves of each trace come from the same function — the -> line before its get_response call, the <- line after it — which is why a middleware naturally holds state across the two phases without storing anything on the request.

Try it: Reverse the list: MIDDLEWARE=["mw.inner", "mw.middle", "mw.outer"]. The function names have not changed; which line comes first and which last? The output starts with -> inner and ends with <- inner, with outer right next to the view. The labels have no power: the position in the list decides who wraps whom, the first entry being the outermost layer.


Returning early skips everything inward

Replace main.py. A blocklist middleware sits in the middle of the chain and answers one path itself.

# main.py
import bootstrap  # noqa: F401
from django.test import Client, override_settings

with override_settings(MIDDLEWARE=["mw.outer", "mw.blocklist", "mw.inner"]):
    print("GET /docks/")
    print("  status:", Client().get("/docks/").status_code)

    print("GET /restricted/   (no route is defined for this path)")
    print("  status:", Client().get("/restricted/").status_code)


GET /docks/
  -> outer
  -> blocklist
  -> inner
    view runs
  <- inner
  <- blocklist
  <- outer
  status: 200
GET /restricted/   (no route is defined for this path)
  -> outer
  -> blocklist
  <- blocklist (short-circuited)
  <- outer
  status: 403


On the blocked request, inner never appears and the view never runs — blocklist returned instead of calling get_response, so the inward half of the onion was never entered. outer still completes its response phase, because it was already suspended inside its own get_response call and simply receives the 403 as the return value. The telling detail is the status: /restricted/ has no route, and the answer is 403, not 404, because the resolver was never reached.

Try it: Move mw.blocklist to the first position: ["mw.blocklist", "mw.outer", "mw.inner"]. For /restricted/, how many lines are still printed, and what happened to outer? Only -> blocklist and <- blocklist (short-circuited) remain, followed by status: 403. outer does not appear at all, neither on the way in nor on the way out: a middleware that short-circuits hides the request from everything below it in the list, so the order also decides which layers get to see a rejected request.


The class form, and catching a view exception

Replace main.py. AuditMiddleware is the same onion written as a class, plus the process_exception hook, against a view that raises.

# main.py
import bootstrap  # noqa: F401
from django.test import Client, override_settings

with override_settings(MIDDLEWARE=["mw.AuditMiddleware"]):
    response = Client().get("/feed/")

print("status:", response.status_code)
print("body  :", response.content.decode())


  -> audit
  process_exception saw: ValueError
  <- audit, status 503
status: 503
body  : degraded


__init__ takes get_response and __call__ handles the request — the factory and the per-request callable, expressed as a class. The ordering shows what process_exception is for: the view raised, Django called the hook before unwinding further, the hook returned a response, and __call__ resumed normally with a status of 503. The exception never propagated through get_response as an exception, which is why a plain function middleware cannot catch a view error with try/except — by the time it sees anything, Django has already turned the failure into a response.


Edge Cases and Gotchas

  • Order in MIDDLEWARE is a dependency order. Anything reading request.user must sit below AuthenticationMiddleware, and anything reading request.session below SessionMiddleware, because the attribute does not exist until that layer has run.
  • The response phase runs even for short-circuited requests. Layers outside the one that returned early still see the response, so a logging middleware placed first records blocked requests too — usually what you want.
  • process_exception only fires for exceptions raised by the view. An exception raised inside another middleware bypasses it and becomes a 500 without the hook being consulted.
  • The factory runs once per process, not per request. State assigned in the outer function is shared by every request the worker handles, which makes it useful for caches and dangerous for anything request-specific.
  • Returning None from the per-request callable breaks the chain. The callable must return a response object; forgetting the return yields an opaque error rather than a helpful one.

Summary

A middleware is a factory that runs once and returns a per-request callable, and the chain is built inside out so that MIDDLEWARE reads top-down on the way in and bottom-up on the way out. Work before get_response is the request phase, work after it is the response phase, and skipping the call entirely skips everything inward.

  • The outer function is called once at startup with the next layer; the inner function it returns handles each request.
  • Django wraps the view with the last MIDDLEWARE entry first, so the first entry ends up outermost and runs earliest inbound and latest outbound.
  • Middleware runs before URL resolution, so a short-circuit can answer a path that has no route — returning 403 where a 404 would otherwise occur.
  • Returning without calling get_response skips all inner layers and the view, while outer layers still complete their response phase.
  • Class-based middleware adds the hooks Django looks up by name; process_exception converts a view exception into a response before the calling layer resumes.

Чтобы получить доступ к облачной лаборатории, необходимо войти в систему.

Войти