0
0
Djangoframework~30 mins

Request/response middleware flow in Django - Mini Project: Build & Apply

Choose your learning style9 modes available
Understanding Request/Response Middleware Flow in Django
📖 Scenario: You are building a simple Django web application that logs messages during the request and response process using middleware. This helps understand how Django processes requests and responses step-by-step.
🎯 Goal: Create a custom middleware class that logs messages when a request is received and when a response is returned. This will demonstrate the flow of request and response through middleware in Django.
📋 What You'll Learn
Create a middleware class named SimpleLoggingMiddleware
Add an __init__ method that accepts get_response and stores it
Add a __call__ method that logs 'Request received' before calling get_response
Log 'Response returned' after getting the response
Return the response from the __call__ method
💡 Why This Matters
🌍 Real World
Middleware is used in Django projects to add functionality like logging, authentication, or modifying requests and responses globally.
💼 Career
Understanding middleware flow is essential for backend developers working with Django to customize request handling and implement cross-cutting concerns.
Progress0 / 4 steps
1
Create the middleware class with __init__
Create a class called SimpleLoggingMiddleware with an __init__ method that takes self and get_response as parameters. Inside __init__, assign get_response to self.get_response.
Django
Need a hint?

The __init__ method stores the next callable in the middleware chain.

2
Add the __call__ method to log request reception
Add a __call__ method to SimpleLoggingMiddleware that takes self and request as parameters. Inside it, print the string 'Request received' before calling self.get_response(request).
Django
Need a hint?

The __call__ method handles the request and must return the response.

3
Log response return after calling next middleware
In the __call__ method, after calling self.get_response(request) and storing it in response, print the string 'Response returned' before returning response.
Django
Need a hint?

Print the message after getting the response but before returning it.

4
Complete middleware and add to Django settings
Ensure the SimpleLoggingMiddleware class is complete as shown. Then, add the string 'yourapp.middleware.SimpleLoggingMiddleware' to the MIDDLEWARE list in your Django settings.py file to activate it.
Django
Need a hint?

Adding the middleware string to MIDDLEWARE activates it in your Django project.