0
0
Djangoframework~10 mins

Creating custom middleware in Django - Visual Walkthrough

Choose your learning style9 modes available
Concept Flow - Creating custom middleware
Request comes in
Middleware __call__ or process_request
View function executes
Middleware process_response
Response sent back to client
Middleware intercepts requests before views and responses after views, allowing custom processing.
Execution Sample
Django
class SimpleMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response
    def __call__(self, request):
        print('Before view')
        response = self.get_response(request)
        print('After view')
        return response
This middleware prints messages before and after the view runs for each request.
Execution Table
StepActionEvaluationResult
1Request received by middleware __call__Print 'Before view'Message logged: Before view
2Call get_response(request) to run viewView processes requestView returns HttpResponse
3After view returnsPrint 'After view'Message logged: After view
4Return response to clientResponse sentClient receives HttpResponse
5End of middleware processingNo further actionRequest cycle complete
💡 Response returned to client after middleware and view processing
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
requestHttpRequest objectSame HttpRequestSame HttpRequestSame HttpRequestSame HttpRequest
responseNoneNoneHttpResponse from viewHttpResponse from viewHttpResponse from view
Key Moments - 2 Insights
Why do we call self.get_response(request) inside __call__?
Calling self.get_response(request) runs the next middleware or the view. Without it, the request would stop and no response would be generated. See execution_table step 2.
What happens if we modify the response after calling get_response?
You can change the response before returning it to the client. This happens after the view runs, as shown in execution_table step 3.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is printed before the view runs?
A'Request received'
B'After view'
C'Before view'
D'Response sent'
💡 Hint
Check step 1 in the execution_table where the first print happens.
At which step does the view function execute?
AStep 2
BStep 1
CStep 3
DStep 4
💡 Hint
Look at the action in step 2 where get_response(request) is called.
If we remove the call to self.get_response(request), what happens?
AThe middleware prints both messages
BNo response is returned to the client
CThe view still runs normally
DThe response is sent twice
💡 Hint
Refer to key_moments about why get_response(request) is necessary.
Concept Snapshot
Creating custom middleware in Django:
- Define a class with __init__(get_response) and __call__(request)
- __call__ runs code before and after calling get_response(request)
- get_response(request) calls the next middleware or view
- Modify request before or response after view
- Return the final response to complete the cycle
Full Transcript
In Django, custom middleware is a class that intercepts requests and responses. When a request comes in, the middleware's __call__ method runs. It can do something before the view by running code before calling get_response(request). Then it calls get_response(request) to run the view or next middleware. After the view returns a response, the middleware can modify or log after the view. Finally, it returns the response to the client. This lets you add custom behavior around every request and response cycle.