Use Django Middlewares right now.

Django Middlewares: Types and Custom Middleware

How does Django middleware works?

  1. Let’s say you want to authenticate a user token in each API call, Some peoples authenticate in every API, but this is not a good way to authenticate, in this case, you can handle the user authentication system in the middleware layer.
  2. Let’s say you have two types of users in your application i.e. free and paid. There are few URLs or views that free users cannot access, so in this case either you can handle free users at every view or you can create a middleware that can handle all the free users in one place.

Types of middleware in Django

  1. Built-in Middlewares.
  2. Custom Middlewares.
  • Security middleware
  • Session middleware
  • Common middleware
  • CSRF protection middleware
  • Authentication middleware
  • Site middleware
  • Cache middleware
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',
]
Python

Description of Middlewares

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',
    # custom middleware
    'todo_app.custom_middleware.CustomMiddleware',
]
Python

  1. Function Based.
  2. Class Based.

Django Middleware: As a function

def custom_request_middleware(get_response):
    # One-time configuration and initialization.

    def middleware(request):
        # Code to be executed for each request before
        # the view (and later middleware) are called.
        print("Before response")
        response = get_response(request)
        print("After response")
        # Code to be executed for each request/response after
        # the view is called.
        return response

    return middleware
Python

Django Middleware: As a Class

class CustomRequestMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response
        # One-time configuration and initialization.

    def __call__(self, request):
        # Code to be executed for each request before
        # the view (and later middleware) are called.

        print("Before response")
        response = self.get_response(request)
        print("After response")
        # Code to be executed for each request/response after
        # the view is called.

        return response
Python

Activate Middleware

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',

    'todo_app.custom_middleware.CustomRequestMiddleware', # Class based custom Middleware
    'todo_app.custom_middleware.custom_request_middleware', # Function based custom Middleware
]
Python

python manage.py runserver
Bash

Starting development server at http://0:8080/
Quit the server with CONTROL-C.
Before response
After response
Bash

Django Middleware structure

class CustomMiddlewareStructure:

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

    def _call_(self, request):
        # Code that is executed in each request before the view is called

        response = self.get_response(request)
        # Code that is executed in each request after the view is called
        return response

    def process_view(self, request, view_func, view_args, view_kwargs):
        # This code is executed just before the view is called
        pass

    def process_exception(self, request, exception):
        # This code is executed if an exception is raised
        pass

    def process_template_response(self, request, response):
        # This code is executed if the response contains a render() method
        return response
Bash

Let’s understand the structure and lifecycle of middleware.

  • __init__(get_response)
  • __call__()
  • process_view(request, view_func, view_args, view_kwargs)
  • process_exception(request, exception)
  • process_template_response(request, response)

Let’s cover each method one by one.

  • If it returns None, Django will continue processing this request, executing any other process_view() middleware and, then, the appropriate view.
  • If it returns an HttpResponse object, Django won’t bother calling the appropriate view, it’ll apply response middleware to that HttpResponse and return the result.
  • If it returns an HttpResponse object, the template response and response middleware will be applied and the resulting response returned to the browser.
  • Otherwise, default exception handling kicks in.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top