0
0
Djangoframework~30 mins

Why middleware matters in Django - See It in Action

Choose your learning style9 modes available
Why middleware matters in Django
📖 Scenario: You are building a simple Django web application that needs to log every request's path and method for monitoring purposes. Middleware is a perfect place to add this logging because it can process requests before they reach your views and responses before they go back to the user.
🎯 Goal: Create a custom Django middleware that logs the HTTP method and path of each incoming request.
📋 What You'll Learn
Create a middleware class named SimpleLoggingMiddleware.
Add a method to process the request and log the HTTP method and path.
Configure the middleware in Django settings.
Ensure the middleware runs on every request.
💡 Why This Matters
🌍 Real World
Middleware is used in real Django projects to handle tasks like logging, authentication, and modifying requests or responses globally.
💼 Career
Understanding middleware is important for backend developers working with Django, as it helps manage cross-cutting concerns efficiently.
Progress0 / 4 steps
1
Create the middleware class
Create a Python class called SimpleLoggingMiddleware inside a file named middleware.py. The class should have an __init__ method that accepts get_response and stores it as an instance variable.
Django
Need a hint?

Middleware classes in Django need an __init__ method that takes get_response and saves it.

2
Add request processing method
Inside the SimpleLoggingMiddleware class, add a __call__ method that takes request as a parameter. Inside this method, log the HTTP method and path using print(f"Method: {request.method}, Path: {request.path}"). Then call and return self.get_response(request).
Django
Need a hint?

The __call__ method lets the middleware process each request. Use print to log the method and path.

3
Configure middleware in settings
Open your Django project's settings.py file. Add the string 'yourapp.middleware.SimpleLoggingMiddleware' to the MIDDLEWARE list. Place it near the top so it runs early.
Django
Need a hint?

Middleware must be listed in the MIDDLEWARE setting to be active.

4
Test middleware by running server
Run the Django development server with python manage.py runserver. Visit any page in your browser. Confirm that the console shows logs like Method: GET, Path: / for each request.
Django
Need a hint?

Use the Django runserver command and watch the terminal for your log messages.