Working with Django middleware
Django middleware is a regular Python class that is hooked into Django’s request/response cycle. Middleware can be used to modify a request before Django views process them or modify a response before sending it back to the client. Every middleware is called twice during the request/response cycle – the first time is when the request is received from the client, and then the second time is when the response is sent back to the client.
By default, Django provides a lot of middleware and we also learned, in Chapter 3, how DRF also utilizes the Django middleware framework to integrate REST APIs. The default Django middleware is mainly used for authentication and is security-related. When we create a new project, Django automatically plugs in this middleware in the settings.py
file:
MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware...