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
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/. MiddlewareMixin declares sync_capable = True and async_capable = True. In MiddlewareMixin, it inspects iscoroutinefunction(self; if the inner callable is async, it sets self and stamps the instance with markcoroutinefunction(self) so the next outer ring sees it as awaitable.
Then MiddlewareMixin 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 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 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: 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 or BaseHandler. Here Django runs three phases that ordinary outer middleware cannot easily perform on its own:
- URL resolution and
process_view: First,BaseHandlerresolves.resolve_request HttpRequestinto.path_info (callback, callback_args, callback_kwargs)and attachesHttpRequest. Only now does Django know which view function is about to run. It loops top-to-bottom over.resolver_match BaseHandler, calling each middleware’s._view_middleware process_viewhook with(request, callback, callback_args, callback_kwargs). That is whyCsrfViewMiddlewareimplementsprocess_viewrather thanprocess_request: it has to inspectgetattr(callback, "csrf_exempt", False)on the resolved view before deciding whether to reject a POST without a CSRF token. If anyprocess_viewreturns a truthyHttpResponse, the loop breaks immediately, skipping any remainingprocess_viewhooks and the view itself. - View execution (with
"ATOMIC_REQUESTS"): If noprocess_viewreturned a response, Django passescallbackthroughBaseHandler, adapts sync/async mode if the view disagrees with the handler, calls the view inside.make_view_atomic try/(passing view exceptions toexcept Exception BaseHandler), and validates the return value with.process_exception_by_middleware BaseHandler..check_response - Deferred rendering and
process_template_response: If the returned response has a callable"render"attribute — such asTemplateResponse— Django loops bottom-to-top overBaseHandler, letting each hook inspect or mutate._template_response_middleware context_dataortemplate_nameand return a response (checked again bycheck_response). Only after everyprocess_template_responsehook finishes does Django callSimpleTemplateResponse, turning the lazy template into HTML bytes — inside another.render try/block so template crashes also reachexcept Exception 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:
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! So although the inner layer’s process_view and the view itself are skipped, the short-circuit response returns out of BaseHandler 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
- Short-circuiting before
SecurityMiddlewareorXFrameOptionsMiddlewaredrops headers. If a custom rate-limit or maintenance middleware sits aboveSecurityMiddlewareand returns a short-circuit response, none of the inner security middlewares run on that response — so the429or503leaves the server without"X-Frame-Options","X-Content-Type-Options", or HSTS headers. process_template_responsesilently skips views usingdjango. Remember Chapter 1:.shortcuts .render djangorenders the template immediately and returns a plain.shortcuts .render HttpResponsewith noSimpleTemplateResponsemethod. Any middleware relying on.render process_template_responsewill execute on generic CBVs (like our newsroom’s EditionListView and StoryDetailView), and silently do nothing on function views usingdjango..shortcuts .render - Forgetting to return a response crashes in
check_response. ReturningNone— or forgettingawaitinside anasync defview so it returns a raw coroutine object — raises a descriptiveValueErrorinsideBaseHandler, which immediately hits the exception wall we open next in Exception walls and error responses..check_response