Middlewares are hooks to modify Django request or response objects. You can use middleware if you want to modify the request i.e HttpRequest object which is sent to the view. Or you might want to modify the HttpResponse object returned from the view. Both these can be achieved by using middleware.
Custom middleware in Django is created either as a function style that takes a get_response callable or a class-based style whose call method is used to process requests and responses. It is created inside a file
middleware.py. A middleware is activated by adding it to the MIDDLEWARE list in Django settings.
Very often you would have used
request.user inside the view. Django wants
user attribute to be set on
request before any view executes. Django takes a middleware approach to accomplish this. So Django provides an
AuthenticationMiddleware which can modify the request object.
Django provides some default 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', ]
How to write your own custom middleware
A middleware factory is a callable that takes a
get_response callable and returns a middleware. A middleware is a callable that takes a request and returns a response, just like a view.
A middleware can be written in two ways
The first step is to create a file
midleware.py inside your app. Mine structure looks like this after creating the file
custom_middleware/ ├── admin.py ├── apps.py ├── __init__.py ├── middleware.py ├── migrations │ └── __init__.py ├── models.py ├── tests.py └── views.py
Now You can follow any of the two ways of creating a middleware as a class or as a function.
Django Middleware: As a function
You can use this function based middleware code snippet inside
def simple_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
Django Middleware: As a Class
You can use this class based middleware code snippet inside
class SimpleMiddleware: 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
Activating Custom Middleware
Activating a middleware is very simple, you have to add it inside the
MIDDLEWARE list in
settings.py. In the middleware list, each middleware component is represented by a string that is the full python path of the middleware. You can add your SimpleMiddleware at the last of the middleware list.
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.middleware.SimpleMiddleware', # Class based custom Middleware 'custom_middleware.middleware.simple_middleware', # Function based custom Middleware ]
Order of the middleware is very important because a middleware can depend on the other middleware. For example Authentication Middleware depends on Session Middleware to store the authenticated user in session (
request.session['user']) therefore, it must be placed after session middleware.
After adding your middleware, run your server and visit the URL
python manage.py runserver 0:8080
Now check your terminal for the
Django version 3.2, using settings 'conf.settings' Starting development server at http://0:8080/ Quit the server with CONTROL-C. before response After response
If you can see the print statements
before response and
After response, it means you have successfully created your own custom Django middleware.
You can check out this
middleware.py file and all the implementation. You can also contribute new or different ways of making and working with middlewares in the same above repository.
Now, you can build a basic middleware but there is more about how Django's middleware works. Therefore let's understand the middleware structure.
Django Middleware Structure
First of all, middleware is a python class or object that is capable of processing each request and response object. Here is a complete structure of a middleware:
class SimpleMiddlewareStructure: 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
Let's understand the structure and lifecycle of middleware.
You can also overwrite these methods instead of
process_view(request, view_func, view_args, view_kwargs)
Let's cover each method one by one.
Only the first two methods,
__call__, are required by the Django framework for your middleware to work properly. The other three are special
hooks that allow you to invoke your middleware under specific conditions. Therefore, the other three are optional.
Method 1: init() in middleware
The first method, init, is the constructor for our Python class. It is called only once, at the time the server starts up. It takes
get_response as a parameter, which is passed by the Django itself when we add it inside the Middleware list like this: 'custom_middleware.middleware.SimpleMiddleware'
Method 2: call() in middleware
__call__() method is called once per request .This method invokes the middleware. Here is what it looks like:
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
You can add validation or feature to the request or response object before or after the view is called.
Method 3: process_view() in middleware
process_view() is called just before Django calls the view.
It should return either
None or an
- 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
HttpResponseobject, Django won’t bother calling the appropriate view; it’ll apply response middleware to that
HttpResponseand return the result.
Method 4: process_exception() in middleware
Django calls process_exception() when a view raises an exception.
process_exception() should return either None or an
- If it returns an
HttpResponseobject, the template response and response middleware will be applied and the resulting response returned to the browser.
- Otherwise, default exception handling kicks in.
Method 5: process_template_response() in middleware
process_template_response() is called just after the view has finished executing if the response instance has a render() method, indicating that it is a TemplateResponse or equivalent.
It must return a response object that implements a
render method. It could alter the given response by changing response.template_name and response.context_data, or it could create and return a brand-new TemplateResponse or equivalent.
That's all about middleware. I hope you like it. You can checkout other django-tutorials.