Django 6.1.3

3.3 Handlers, middleware, and async

MiddlewareMixin and short-circuits

How do process_request, process_view, process_template_response, and process_response fit into modern callable middleware, and what skips when a layer returns early?

Modern Django middleware is supposed to be a simple callable taking get_response and returning a function of request. Yet when we inspected all seven built-in middleware classes in "desk.settings" in the previous section, every single one of them — SecurityMiddleware, SessionMiddleware, CommonMiddleware, CsrfViewMiddleware, AuthenticationMiddleware, MessageMiddleware, and XFrameOptionsMiddleware — inherited from MiddlewareMixin.

Ten years after Django replaced "MIDDLEWARE_CLASSES" with "MIDDLEWARE", the “deprecation” mixin is still the backbone of Django’s own default stack. To understand how hooks, short-circuits, and ASGI thread crossings behave, you have to open MiddlewareMixin itself.

Why DEP 0005 changed the rules

Figure 3.2 Every step count is parsed from ch03-handlers. The hatched outer edge of every ring marks the convert_exception_to_response boundary installed by BaseHandler.load_middleware; the dashed red U-turn shows DEP 0005’s short-circuit symmetry when the middle layer’s process_request returns early.

Inside MiddlewareMixin.__call__

Open lines 408–464 of django/utils/deprecation.py. MiddlewareMixin declares sync_capable = True and async_capable = True. In MiddlewareMixin.__init__, it inspects iscoroutinefunction(self.get_response); if the inner callable is async, it sets self.async_mode = True and stamps the instance with markcoroutinefunction(self) so the next outer ring sees it as awaitable.

Then MiddlewareMixin.__call__ bridges the old hook methods into the new callable contract in seven lines:

def __call__(self, request):
    if self.async_mode:
        return self.__acall__(request)
    response = None
    if hasattr(self, "process_request"):
        response = self.process_request(request)
    response = response or self.get_response(request)
    if hasattr(self, "process_response"):
        response = self.process_response(request, response)
    return response

Read those three if/or lines slowly, because every nuance of request-phase short-circuiting sits right there. If process_request returns None (the common case), response or self.get_response(request) calls the next inner ring of the onion. If process_request returns an HttpResponse — a short-circuit response (such as an HTTPS redirect in SecurityMiddleware, a cached page in FetchFromCacheMiddleware, or a rate-limit 429) — the or operator skips MiddlewareMixin.get_response completely. Yet notice the very next line: process_response STILL runs on the middleware that short-circuited, and then every outer middleware’s process_response runs as the call stack unwinds.

Now glance five lines lower at MiddlewareMixin.__acall__: it executes the exact same logic, except it wraps process_request and process_response individually in await sync_to_async(..., thread_sensitive=True). That innocent-looking compatibility shim is what produces 13 thread-pool crossings on Django’s default ASGI stack.

The core hooks: process_view and process_template_response

When no process_request short-circuits, the request reaches the centre of the onion: BaseHandler._get_response or BaseHandler._get_response_async. Here Django runs three phases that ordinary outer middleware cannot easily perform on its own:

  1. URL resolution and process_view: First, BaseHandler.resolve_request resolves HttpRequest.path_info into (callback, callback_args, callback_kwargs) and attaches HttpRequest.resolver_match. Only now does Django know which view function is about to run. It loops top-to-bottom over BaseHandler._view_middleware, calling each middleware’s process_view hook with (request, callback, callback_args, callback_kwargs). That is why CsrfViewMiddleware implements process_view rather than process_request: it has to inspect getattr(callback, "csrf_exempt", False) on the resolved view before deciding whether to reject a POST without a CSRF token. If any process_view returns a truthy HttpResponse, the loop breaks immediately, skipping any remaining process_view hooks and the view itself.
  2. View execution (with "ATOMIC_REQUESTS"): If no process_view returned a response, Django passes callback through BaseHandler.make_view_atomic, adapts sync/async mode if the view disagrees with the handler, calls the view inside try/except Exception (passing view exceptions to BaseHandler.process_exception_by_middleware), and validates the return value with BaseHandler.check_response.
  3. Deferred rendering and process_template_response: If the returned response has a callable "render" attribute — such as TemplateResponse — Django loops bottom-to-top over BaseHandler._template_response_middleware, letting each hook inspect or mutate context_data or template_name and return a response (checked again by check_response). Only after every process_template_response hook finishes does Django call SimpleTemplateResponse.render, turning the lazy template into HTML bytes — inside another try/except Exception block so template crashes also reach process_exception!

Comparing all three traces live

Instrument three MiddlewareMixin layers (outer, middle, inner) around a view returning a TemplateResponse, and record a full pass against short-circuits in process_request and process_view:

Recorded on Django 6.1.3 ch03-handlers script
Onion hook ordering: full pass vs process_request and process_view short-circuits
  Full pass (TemplateResponse view) -> 200 OK (rendered-body):
    01. Outer.process_request
    02. Middle.process_request
    03. Inner.process_request
    04. Outer.process_view
    05. Middle.process_view
    06. Inner.process_view
    07. view.probe_view
    08. Inner.process_template_response
    09. Middle.process_template_response
    10. Outer.process_template_response
    11. TemplateResponse.render
    12. Inner.process_response(status=200)
    13. Middle.process_response(status=200)
    14. Outer.process_response(status=200)
  
  Short-circuit in Middle.process_request -> 200 OK (short-circuited in process_request):
    01. Outer.process_request
    02. Middle.process_request
    03. Middle.process_request -> SHORT-CIRCUIT 200
    04. Middle.process_response(status=200)
    05. Outer.process_response(status=200)
  
  Short-circuit in Middle.process_view -> 200 OK (short-circuited in process_view):
    01. Outer.process_request
    02. Middle.process_request
    03. Inner.process_request
    04. Outer.process_view
    05. Middle.process_view
    06. Middle.process_view -> SHORT-CIRCUIT 200
    07. Inner.process_response(status=200)
    08. Middle.process_response(status=200)
    09. Outer.process_response(status=200)

Compare the second and third traces carefully — they highlight a subtle distinction engineers frequently mispredict.

When the middle layer short-circuits in process_request (5 steps), the inner layer was never entered, so Inner’s process_request and process_response are both skipped. When the middle layer short-circuits in process_view (9 steps), all three process_request methods have already run to reach BaseHandler._get_response! So although the inner layer’s process_view and the view itself are skipped, the short-circuit response returns out of BaseHandler._get_response into the inner layer’s waiting stack frame — meaning Inner’s process_response still runs (step 07), followed by Middle’s and Outer’s process_response.

Where hooks and short-circuits leak