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 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 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 executes around that contract on our newsroom endpoint "/wire/status/":
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:
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_wsgiimmediately re-encodes them back to raw bytes and decodes as UTF-8.request_startedfires synchronously viaSignal.sendwithenviron. Django’s database layer listens here to reset query logs and drop expired database connections before the view runs.WSGIRequest(environ)wraps the raw dictionary without parsing query strings, cookies, or POST bodies yet. It wrapsenviron["wsgiinside a.input"] LimitedStreamcapped at"CONTENT_LENGTH"bytes so reading the request body cannot hang waiting for EOF on a keep-alive socket.BaseHandlersets the thread-local root URLconf via.get_response set_urlconf, invokesBaseHandlerwith the request, appends._middleware_chain HttpRequestto.close _resource_closers, and logs any response with status>= 400.WSGIHandlerstamps.__call__ response, formats._handler_class = self .__class__ "200 OK"plus headers (including one"Set-Cookie"tuple per cookie), callsstart_response(status, response_headers), and returns the response object itself — which is still open (closed=False)!- Notice what happened between step 5 and
request_finishedin our trace:WSGIHandlerdoes not emit.__call__ request_finished. PEP 3333 obligates the WSGI server to iterate the returned response and then callHttpResponseBase. Only inside.close HttpResponseBasedoes Django drain.close _resource_closers(closing uploaded temporary files), flipclosed = True, and firerequest_finished— which runsreset_urlconfand 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 and "http dictionaries.
Run the exact same "/wire/status/" endpoint through ASGIHandler and compare its lifecycle:
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 and ASGIHandler solve four problems WSGI never faces.
First, ASGIHandler 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 drains all "http.request" chunks from "receive" into a tempfile capped at settings (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 so disk I/O does not stall the event loop.
Third, once ASGIHandler constructs ASGIRequest (or short-circuits directly to a 400 on UnicodeDecodeError or 413 on RequestDataTooBig, ASGIHandler), Django launches two concurrent coroutines inside an asyncio:
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 pattern is unusually clever. While ASGIHandler and ASGIHandler execute, ASGIHandler sits parked on await receive(). If the request finishes normally, raising the local "RequestProcessed" sentinel tears down the asyncio and cancels the disconnect listener. If the client closes its TCP socket mid-request, listen_for_disconnect receives "http and raises RequestAborted, causing the asyncio to inject asyncio into the running view immediately!
Both the disk rollover and both disconnect paths verify cleanly on Django 6.1.3:
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 encodes header keys as ASCII and values as Latin-1, sends "http, and slices ordinary bodies into 64 KiB chunks (ASGIHandler, 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 message. Finally, lines 215–218 close the request cleanly: if a response exists, await sync_to_async(response runs _resource_closers and request_finished; if the client disconnected before a response was built (response is None), Django fires await signals directly — exactly as the "mid-request http trace confirmed.
Where the entry-point abstraction leaks
Compare the two handlers side by side and three sharp edge cases jump out:
- WSGI owns
close(), not Django. If a custom test harness or WSGI wrapper callsWSGIHandlerdirectly and reads bytes without callingHttpResponseBase,.close request_finishednever fires — leaking database connections, leavingset_urlconfpolluted for the next request on that thread, and keeping uploaded temp files open. - ASGI buffers the full request body before middleware runs. Unlike WSGI — where
LimitedStreamreads lazily from"wsgi.input"only if a view touchesHttpRequest.bodyorWSGIRequest.POST—ASGIHandlerawaits every.read_body "http.request"chunk beforecreate_requestor any middleware executes. You cannot use ASGI middleware to reject a500 MiBupload early by checking"Content-Length"before the server finishes receiving the bytes intotempfile..SpooledTemporaryFile - ASGI headers drop underscores silently. Look at lines 94–95 of
django/:core/ handlers/ asgi .py ASGIRequestexplicitly ignores any incoming header whose name contains.__init__ "_"to prevent spoofing ambiguity with hyphens ("X-Auth"vs"X_Auth"both mapping to"HTTP_X_AUTH"inMETA).
Inside both handlers, the very first line of __init__ called BaseHandler to construct _middleware_chain. Let’s open that loop next in Building the middleware onion.