Implementing Custom Middleware in Django

Middlewares in Django are the framework of hooks into its request/response processing. Django provides various built-in middlewares and flexibility to write our own middleware. There are just 2 simple steps to implement custom middleware.

Writing your own middleware

  • Step 1:
    Create a class that:
    • Accepts get_response as an argument in its constructor
    • Implements a method __call__ which takes request as an argument and returns response at the end.

file_name.py

class CustomMiddleware():

    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
    
        # Code block that is executed in each request before the view is executed
     
        response = self.get_response(request)
        
        # Code block that is executed in each request after the view is executed
        return response
  • Step 2:
    Add this class to MIDDLEWARE list inside the settings.py file.
    (Note: the ordering of middleware is important)

settings.py

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'file_name.CustomMiddleware',  # Listed custom middleware
    ]

& We're Done!

Demonstration

For more clarity and understanding, let's implement SetHttpHeaders class which sets the response header after the view function is executed.

class SetHttpHeadersMiddleware():

    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
    
        response = self.get_response(request)

        response['Connections'] = "keep-alive"
        response['Expect-CT'] = "max-age=0"
        response['Pragma'] = "no-cache"
        response['Cache-Control'] = "no-store, no-cache, max-age=0, must-revalidate, post-check=0, pre-check=0"

        return response

As mentioned above, list this class under middleware list in settings.py to activate this middleware.
Finally, Using Postman or other tool, Test any route linked to view function which implements this middleware and check the response headers.

Output:
Postman-Response-headers

Kartik Kapgate

Kartik Kapgate

Software Engineer | Backend