Django 6.1.3

3.1 Handlers, middleware, and async

WSGI and ASGI entry points

How do WSGIHandler and ASGIHandler turn a server’s raw environment dictionary or ASGI scope into a Django request and stream the response back?

Every Django deployment begins with a six-line file that looks almost identical whether you run Gunicorn or Uvicorn. Our newsroom project exposes get_wsgi_application for synchronous servers and get_asgi_application for asynchronous servers. Both functions do exactly two things: they call django.setup(set_prefix=False) and return one long-lived handler instance — either WSGIHandler or ASGIHandler.

Why do both entry points pass set_prefix=False to django.setup? In Chapter 2, django.setup used FORCE_SCRIPT_NAME (or "/") to set a process-wide URL prefix for management commands that have no incoming HTTP request. A web worker serves requests that can carry a different mount prefix ("SCRIPT_NAME" in WSGI, "root_path" in ASGI) on every single call, so both handlers overwrite the active prefix at the start of each request rather than fixing it once at startup.

Both handlers subclass BaseHandler and call BaseHandler.load_middleware inside __init__ — is_async=False for WSGIHandler, is_async=True for ASGIHandler. From that point forward, the handler object is reused across every request the worker handles.

WSGIHandler: synchronous dictionary in, iterable out

WSGI (Web Server Gateway Interface, PEP 3333) models an HTTP exchange as one blocking Python call: the server passes a dictionary of CGI-style strings (environ) and a callback (start_response), and the application returns an iterable of bytes chunks. Look at what WSGIHandler.__call__ executes around that contract on our newsroom endpoint "/wire/status/":

Recorded on Django 6.1.3 ch03-handlers script
WSGIHandler vs ASGIHandler on GET /wire/status/
  WSGIHandler lifecycle:
    signal request_started sender=WSGIHandler arg=environ
    start_response status='200 OK' headers=7
    handler returned JsonResponse _handler_class=WSGIHandler closed=False
    signal request_finished sender=WSGIHandler
    after resp.close() closed=True body={"editions": 2, "published_stories": 5, "latest_edition": "2026-11-25"}
    headers=['Content-Type=application/json', 'X-Frame-Options=DENY', 'Content-Length=71', 'X-Desk-Ms=<elapsed_ms>', 'X-Content-Type-Options=nosniff', 'Referrer-Policy=same-origin', 'Cross-Origin-Opener-Policy=same-origin']

Trace those six steps against the source lines of WSGIHandler.__call__:

  1. set_script_prefix(get_script_name(environ)) extracts the active mount prefix from "FORCE_SCRIPT_NAME", Apache’s "SCRIPT_URL"/"REDIRECT_URL", or "SCRIPT_NAME". Because PEP 3333 forces non-ASCII WSGI strings to be decoded as "iso-8859-1", get_bytes_from_wsgi immediately re-encodes them back to raw bytes and decodes as UTF-8.
  2. request_started fires synchronously via Signal.send with environ. Django’s database layer listens here to reset query logs and drop expired database connections before the view runs.
  3. WSGIRequest(environ) wraps the raw dictionary without parsing query strings, cookies, or POST bodies yet. It wraps environ["wsgi.input"] inside a LimitedStream capped at "CONTENT_LENGTH" bytes so reading the request body cannot hang waiting for EOF on a keep-alive socket.
  4. BaseHandler.get_response sets the thread-local root URLconf via set_urlconf, invokes BaseHandler._middleware_chain with the request, appends HttpRequest.close to _resource_closers, and logs any response with status >= 400.
  5. WSGIHandler.__call__ stamps response._handler_class = self.__class__, formats "200 OK" plus headers (including one "Set-Cookie" tuple per cookie), calls start_response(status, response_headers), and returns the response object itself — which is still open (closed=False)!
  6. Notice what happened between step 5 and request_finished in our trace: WSGIHandler.__call__ does not emit request_finished. PEP 3333 obligates the WSGI server to iterate the returned response and then call HttpResponseBase.close. Only inside HttpResponseBase.close does Django drain _resource_closers (closing uploaded temporary files), flip closed = True, and fire request_finished — which runs reset_urlconf and closes old database connections.

ASGIHandler: coroutines, spooling, and cancellation

ASGI (Asynchronous Server Gateway Interface) splits a single HTTP connection into three arguments passed to an async def callable: a scope dictionary describing the connection, an async "receive" coroutine yielding incoming body chunks or disconnect events, and an async "send" coroutine accepting "http.response.start" and "http.response.body" dictionaries.

Run the exact same "/wire/status/" endpoint through ASGIHandler.__call__ and compare its lifecycle:

Recorded on Django 6.1.3 ch03-handlers script
  ASGI non-http scope -> ValueError: Django can only handle ASGI/HTTP connections, not websocket.
  ASGIHandler lifecycle:
    signal request_started sender=ASGIHandler arg=scope
    signal request_finished sender=ASGIHandler
    send http.response.start status=200 headers=['Content-Type=application/json', 'X-Frame-Options=DENY', 'Content-Length=71', 'X-Desk-Ms=<elapsed_ms>', 'X-Content-Type-Options=nosniff', 'Referrer-Policy=same-origin', 'Cross-Origin-Opener-Policy=same-origin']
    send http.response.body bytes=71 more_body=False body={"editions": 2, "published_stories": 5, "latest_edition": "2026-11-25"}

Under the hood, ASGIHandler.__call__ and ASGIHandler.handle solve four problems WSGI never faces.

First, ASGIHandler.__call__ rejects any non-"http" scope (such as "websocket" or "lifespan") with ValueError and wraps the entire request inside async with ThreadSensitiveContext():. That context manager is the reason every synchronous middleware and ORM query inside one ASGI request stays pinned to a dedicated per-request worker thread instead of scattering across a shared thread pool; we open its machinery in Sync and async inside one chain.

Second, before building ASGIRequest or invoking any middleware, ASGIHandler.read_body drains all "http.request" chunks from "receive" into a tempfile.SpooledTemporaryFile capped at settings.FILE_UPLOAD_MAX_MEMORY_SIZE (2.5 MiB by default). While the payload fits in RAM, writing chunks runs inline on the event loop; the instant the buffer overflows onto disk ("_rolled" becomes True), Django switches each write to sync_to_async(body_file.write, thread_sensitive=False) so disk I/O does not stall the event loop.

Third, once ASGIHandler.create_request constructs ASGIRequest (or short-circuits directly to a 400 on UnicodeDecodeError or 413 on RequestDataTooBig, ASGIHandler.create_request), Django launches two concurrent coroutines inside an asyncio.TaskGroup:

async with asyncio.TaskGroup() as tg:
    tg.create_task(self.listen_for_disconnect(receive))
    response = await self.run_get_response(request)
    await self.send_response(response, send)
    raise RequestProcessed

That asyncio.TaskGroup pattern is unusually clever. While ASGIHandler.run_get_response and ASGIHandler.send_response execute, ASGIHandler.listen_for_disconnect sits parked on await receive(). If the request finishes normally, raising the local "RequestProcessed" sentinel tears down the asyncio.TaskGroup and cancels the disconnect listener. If the client closes its TCP socket mid-request, listen_for_disconnect receives "http.disconnect" and raises RequestAborted, causing the asyncio.TaskGroup to inject asyncio.CancelledError into the running view immediately!

Both the disk rollover and both disconnect paths verify cleanly on Django 6.1.3:

Recorded on Django 6.1.3 ch03-handlers script
ASGIHandler body spooling (RAM vs disk rollover) and client disconnect
  read_body limit=1024 payload=512B  -> _rolled=False bytes_read=512
  read_body limit=1024 payload=1200B -> _rolled=True bytes_read=1200
  early http.disconnect in read_body -> get_response_async_called=False messages_sent=0
  mid-request http.disconnect -> view_cancelled=True messages_sent=0 signals=['request_finished sender=ASGIHandler']

Fourth, ASGIHandler.send_response encodes header keys as ASCII and values as Latin-1, sends "http.response.start", and slices ordinary bodies into 64 KiB chunks (ASGIHandler.chunk_bytes, chunk_size = 2**16) so huge responses do not monopolize a single event-loop turn. For streaming responses, it consumes async with aclosing(aiter(response)) and finishes with an empty "http.response.body" message. Finally, lines 215–218 close the request cleanly: if a response exists, await sync_to_async(response.close)() runs _resource_closers and request_finished; if the client disconnected before a response was built (response is None), Django fires await signals.request_finished.asend(sender=self.__class__) directly — exactly as the "mid-request http.disconnect" trace confirmed.

Where the entry-point abstraction leaks

Compare the two handlers side by side and three sharp edge cases jump out:

Inside both handlers, the very first line of __init__ called BaseHandler.load_middleware to construct _middleware_chain. Let’s open that loop next in Building the middleware onion.