Part I · The request
Chapter 2: Handlers, middleware, and async
The promiseA request is a function call.
The machineryA WSGIHandler or ASGIHandler turns a flat list of middleware strings into a nested chain of callables around the view, trapping exceptions at every layer and bridging sync and async across threads.
Django never opens a listening socket. A server owns the wire and hands each request to a single callable object: the handler. When that handler starts, BaseHandler builds BaseHandler from the inside out, wrapping the centre view resolver in each layer listed in settings.
The onion and its boundaries
Each middleware layer receives a request on the way in, invokes the inner callable, and inspects or replaces the response on the way out. Because BaseHandler wraps every layer separately in convert_exception_to_response, an unhandled exception inside one layer becomes an HTTP response before the outer layer ever sees it.
Crossing between event loop and thread
Under ASGIHandler, synchronous middleware and synchronous views cannot run directly on the event loop without blocking every other connection. Django inspects sync_capable and async_capable on each layer and adapts mismatches with sync_to_async or async_to_sync. Each mode change along the chain crosses between the event loop and a worker thread, turning an invisible middleware ordering choice into measurable request latency.