Sobes.tech
Middle

What is middleware in Django, what is it used for, what standard middleware do you know, give an example of custom middleware?

sobes.tech AI

Answer from AI

Middleware in Django are components that process requests and responses between the server and the application. They allow you to perform common tasks such as authentication, sessions, caching, error handling, logging, etc., without having to write this code in each view.

Standard middleware in Django includes:

  • SecurityMiddleware — provides security features (e.g., HTTPS).
  • SessionMiddleware — supports sessions.
  • CommonMiddleware — various common functions, such as redirects.
  • CsrfViewMiddleware — protects against CSRF attacks.
  • AuthenticationMiddleware — associates a user with the request.
  • MessageMiddleware — supports the messaging system.

An example of custom middleware that logs the processing time of a request:

import time

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

    def __call__(self, request):
        start_time = time.time()
        response = self.get_response(request)
        duration = time.time() - start_time
        print(f"Request to {request.path} took {duration:.4f} seconds")
        return response

To use middleware, add its class to the MIDDLEWARE list in Django settings.