0
0
Djangoframework~5 mins

Why middleware matters in Django

Choose your learning style9 modes available
Introduction

Middleware helps Django handle tasks before and after a web request. It makes your app smarter and easier to manage.

You want to check if a user is logged in before showing a page.
You need to add special headers to every response from your site.
You want to log details about each visitor automatically.
You want to block bad users or bots from accessing your site.
You want to modify requests or responses without changing your main code.
Syntax
Django
class MyMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        # Code before view runs
        response = self.get_response(request)
        # Code after view runs
        return response

The __init__ method runs once when the server starts.

The __call__ method runs for each request, letting you add code before and after the view.

Examples
This middleware prints messages before and after the view runs.
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 adds a custom header to every response.
Django
class AddHeaderMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)
        response['X-Custom-Header'] = 'Hello'
        return response
Sample Program

This middleware logs the URL path of each request and the status code of the response.

Django
class LogMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        print(f'Received request: {request.path}')
        response = self.get_response(request)
        print(f'Sent response with status: {response.status_code}')
        return response
OutputSuccess
Important Notes

Middleware runs in the order listed in settings.MIDDLEWARE.

Middleware can change requests and responses, so use it carefully.

Always return the response object from your middleware.

Summary

Middleware lets you add code before and after views run.

It helps with tasks like logging, security, and modifying responses.

Middleware makes your Django app easier to manage and extend.