What is the Django request/response cycle and how does middleware fit in?
Understand the Django request/response cycle, how middleware wraps views in and out, MIDDLEWARE ordering and WSGI/ASGI, with examples and interview questions.
Expected Interview Answer
The Django request/response cycle is the path an HTTP request travels from the WSGI/ASGI server through middleware, URL routing, and the view, then back out as an HttpResponse — with middleware acting as layered hooks that wrap the view to process every request on the way in and every response on the way out.
When a request arrives, the WSGI/ASGI handler builds an HttpRequest and passes it down the middleware stack top to bottom; each middleware can inspect, modify, short-circuit, or annotate the request before the URL resolver matches a pattern and calls the view. The view returns an HttpResponse, which then travels back up through the same middleware in reverse order, letting each layer alter headers, cookies, or the body. Middleware is configured as an ordered list in the MIDDLEWARE setting, and ordering matters because outer layers see the request first and the response last.
- Central place for cross-cutting concerns like auth, sessions, and CSRF
- Clear, predictable ordering of request and response processing
- Views stay focused on business logic, not plumbing
- Easy to short-circuit requests early (redirects, blocks)
- Reusable, pluggable layers you can add or remove per project
AI Mentor Explanation
Think of a delivery reaching the batter: the ball passes the umpire, the fielding restrictions, and the pitch conditions before it is actually played, then the outcome travels back through the scorer and the third umpire for review. Django middleware is those officiating layers — each one inspects the incoming request, the view plays the shot, and the response passes back through the same officials in reverse to be validated and recorded.
Step-by-Step Explanation
Step 1
Server builds the request
The WSGI or ASGI handler wraps the raw HTTP data into an HttpRequest object.
Step 2
Request descends middleware
Each middleware in MIDDLEWARE runs top to bottom, able to modify or short-circuit the request.
Step 3
URL resolver matches a view
Django's URLconf maps the path to a view function or class, extracting any captured parameters.
Step 4
View returns a response
The view runs business logic and returns an HttpResponse (or raises an exception middleware can handle).
Step 5
Response ascends middleware
The response passes back up through middleware in reverse order, letting each layer adjust headers or body.
Step 6
Server sends the response
The handler serializes the final HttpResponse back to the client.
What Interviewer Expects
- Correct in-then-out flow through the middleware stack
- Awareness that MIDDLEWARE order is significant
- Role of the URL resolver between middleware and the view
- Knowledge that middleware can short-circuit a request
- Distinction between WSGI and ASGI entry points
Common Mistakes
- Thinking middleware runs only before the view, not after
- Ignoring that middleware executes in reverse on the response
- Confusing middleware with view decorators
- Assuming ordering in MIDDLEWARE does not matter
- Believing every request always reaches a view
Best Answer (HR Friendly)
“In Django, a web request travels through a series of layers called middleware before it reaches the code that builds the page, and the finished page travels back out through those same layers. Middleware handles common jobs like login checks and security so the main page code can stay simple.”
Code Example
class TimingMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
# runs on the way in
request.start_time = time.monotonic()
response = self.get_response(request) # calls the view
# runs on the way out
response['X-Elapsed'] = str(time.monotonic() - request.start_time)
return responseFollow-up Questions
- How does middleware order affect authentication and session handling?
- What is the difference between WSGI and ASGI in Django?
- How do process_view and process_exception hooks work?
- How would you short-circuit a request in middleware?
- How does Django handle exceptions raised inside a view?
MCQ Practice
1. In what order does middleware process the outgoing response?
Middleware processes requests top to bottom but responses bottom to top, so the outermost layer sees the response last.
2. Which component matches a request path to a view?
After middleware, Django's URL resolver matches the path against URLconf patterns to select the view.
3. What must a modern Django middleware's __call__ return?
The __call__ method receives the request and must return an HttpResponse, typically from self.get_response(request).
Flash Cards
What is Django middleware? — Ordered layers that process every request on the way in and every response on the way out, wrapping the view.
Does MIDDLEWARE order matter? — Yes — outer layers see the request first and the response last, so order changes behavior.
What sits between middleware and the view? — The URL resolver (URLconf), which matches the path to a view.
Can middleware stop a request early? — Yes — it can return a response directly without ever calling the view.