---
django: 6.1.3 (f16e25dcb9fe55734ba4ea2b00ac34405b7df74a)
---

# 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` (`django/core/wsgi.py:get_wsgi_application`) for synchronous servers and `get_asgi_application` (`django/core/asgi.py: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`** (`django/core/handlers/wsgi.py:WSGIHandler`) or **`ASGIHandler`** (`django/core/handlers/asgi.py: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` (`django/core/handlers/base.py: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__` (`django/core/handlers/wsgi.py:WSGIHandler.__call__`) executes around that contract on our newsroom endpoint `"/wire/status/"`:

```text recording=ch03-handlers
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))` (`django/urls/base.py:set_script_prefix`, `django/core/handlers/wsgi.py:get_script_name`) 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` (`django/core/handlers/wsgi.py:get_bytes_from_wsgi`) immediately re-encodes them back to raw bytes and decodes as UTF-8.
2. `request_started` (`django/core/signals.py:request_started`) fires synchronously via `Signal.send` (`django/dispatch/dispatcher.py: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)` (`django/core/handlers/wsgi.py:WSGIRequest.__init__`) wraps the raw dictionary without parsing query strings, cookies, or POST bodies yet. It wraps `environ["wsgi.input"]` inside a `LimitedStream` (`django/core/handlers/wsgi.py: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` (`django/core/handlers/base.py:BaseHandler.get_response`) sets the thread-local root URLconf via `set_urlconf`, invokes `BaseHandler._middleware_chain` with the request, appends `HttpRequest.close` (`django/http/request.py: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` (`django/core/signals.py:request_finished`). PEP 3333 obligates the WSGI server to iterate the returned response and then call `HttpResponseBase.close` (`django/http/response.py: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` (`django/core/handlers/base.py:reset_urlconf`) and closes old database connections.

> **Deeper.** Look at lines 134–143 of `django/core/handlers/wsgi.py`. When a view returns a `FileResponse` (`file_to_stream` is set) and the WSGI server supplies `"wsgi.file_wrapper"` (for zero-copy `"sendfile"` support), the server calls `HttpResponseBase.close` only via the file wrapper rather than on the Django `HttpResponse`. To keep `request_finished` from silently disappearing on every file download, Django monkey-patches `response.file_to_stream.close = response.close` before handing the file to `"wsgi.file_wrapper"`.

## `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__` (`django/core/handlers/asgi.py:ASGIHandler.__call__`) and compare its lifecycle:

```text recording=ch03-handlers
  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` (`django/core/handlers/asgi.py: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():` (`asgiref:asgiref/sync.py: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](async-bridge.md).

Second, before building `ASGIRequest` (`django/core/handlers/asgi.py:ASGIRequest.__init__`) or invoking any middleware, `ASGIHandler.read_body` (`django/core/handlers/asgi.py: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`, `django/core/handlers/asgi.py:ASGIHandler.create_request`), Django launches two concurrent coroutines inside an `asyncio.TaskGroup`:

```python
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` (`django/core/handlers/asgi.py:ASGIHandler.run_get_response`) and `ASGIHandler.send_response` (`django/core/handlers/asgi.py:ASGIHandler.send_response`) execute, `ASGIHandler.listen_for_disconnect` (`django/core/handlers/asgi.py: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` (`django/core/exceptions.py: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`:

```text recording=ch03-handlers
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:

- **WSGI owns `close()`, not Django.** If a custom test harness or WSGI wrapper calls `WSGIHandler` directly and reads bytes without calling `HttpResponseBase.close`, `request_finished` never fires — leaking database connections, leaving `set_urlconf` polluted 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 `LimitedStream` reads lazily from `"wsgi.input"` only if a view touches `HttpRequest.body` or `WSGIRequest.POST` — `ASGIHandler.read_body` awaits every `"http.request"` chunk before `create_request` or any middleware executes. You cannot use ASGI middleware to reject a `500 MiB` upload early by checking `"Content-Length"` before the server finishes receiving the bytes into `tempfile.SpooledTemporaryFile`.
- **ASGI headers drop underscores silently.** Look at lines 94–95 of `django/core/handlers/asgi.py`: `ASGIRequest.__init__` explicitly ignores any incoming header whose name contains `"_"` to prevent spoofing ambiguity with hyphens (`"X-Auth"` vs `"X_Auth"` both mapping to `"HTTP_X_AUTH"` in `META`).

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](the-onion.md).
