Code-Memo

Middleware

Understanding Middleware

Middleware is a series of hooks that process requests and responses globally before they reach views or after they leave them. Each middleware component is a Python class that interacts with requests and responses.

Every middleware class must implement at least one of the following methods:

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

Middleware components are listed in MIDDLEWARE inside settings.py.

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.middleware.common.CommonMiddleware',
    'myapp.middleware.SimpleMiddleware',
]