In Django, a request is handled by the WSGI/ASGI handler, wrapped by a stack of middleware, routed by the URL resolver to a view, and turned into an HttpResponse that flows back out through the same middleware in reverse.
In Django, a request is handled by the WSGI/ASGI handler, wrapped by a stack of middleware, routed by the URL resolver to a view, and turned into an HttpResponse that flows back out through the same middleware in reverse.
Web server ──▶ WSGI/ASGI handler (creates HttpRequest)
▼
Middleware — request phase (top → bottom: __call__ before get_response)
▼
URL resolver (urls.py) ── match path → view + kwargs
▼
Middleware — process_view hook
▼
View (function / class-based) ── your logic, returns HttpResponse
▼
Middleware — response phase (bottom → top: after get_response)
▼
HttpResponse ──▶ client
HttpRequest from the environ/scope.get_response() runs top-to-bottom (SecurityMiddleware, SessionMiddleware, AuthenticationMiddleware, CSRF, …). Any of them can short-circuit and return a response early.ROOT_URLCONF patterns are matched against the path to select a view and capture kwargs.process_view — a middleware hook that runs just before the view is called.HttpResponse. Exceptions trigger process_exception.get_response() runs bottom-to-top, letting middleware modify the outgoing response (headers, compression).HttpResponse is streamed back to the server and client.# middleware.py
class TimingMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request): # 2. request phase (before)
request.started = time.monotonic()
response = self.get_response(request) # calls the next layer / view
response["X-Time"] = "..." # 6. response phase (after)
return response
# urls.py → 3. routing
urlpatterns = [path("items/<int:pk>/", views.item_detail)]
# views.py → 5. view
def item_detail(request, pk):
return render(request, "item.html", {"item": Item.objects.get(pk=pk)})
Django's request/response cycle is middleware-centric, so most cross-cutting behavior — auth, sessions, CSRF, security headers, caching — is implemented as ordered middleware. Understanding that request-phase code runs top-down and response-phase code runs bottom-up (and that ordering in MIDDLEWARE matters) is essential to placing your own middleware correctly, debugging why a 403/redirect happens before your view, and knowing where to hook logic without touching every view.
A library of IT interview questions with detailed answers — from Junior to Senior.
Donate