Everything about Custom Middleware in Django
So, In this article, we’ll learn about Middleware in Django, why to use them, how it works & how to create custom middleware in Django. So, let’s dive in!
Middleware in Django
- In Django, middleware is a lightweight plugin that processes during request and response execution.
- Middleware is used to perform a function in the application. The functions can be security, session, CSRF protection, authentication, etc.
Types of Middleware
There are two types of Middleware in Django:
- Built-in Middleware
- Custom Middleware
Built-in Middleware is provided by default in Django when you create your project. You can check the default Middleware in settings.py
the file of your project.
#built-in moddleware's
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',
]
You can write your own Custom Middleware for your project. Custom Middleware can be Function-based or Class-based
Function-based Middleware
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.
response = get_response(request) # Code to be executed for each request after
# the view are called.
return response return middleware
Class-based Middleware
class CustomMiddleware:
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
print("custom middleware before next middleware/view")
# Code to be executed for each request before
# the view (and later middleware) are called.
response = self.get_response(request)
# Code to be executed for each request after
# the view are called. print("custom middleware after middleware/view")
return response
- Once you have written the middleware code, you would have to plug it into your Django request/response flow. You need to add the entry to
setting.py
fileMIDDLEWARE
section.
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', # your custom middleware
'your_app.custom_middleware_file.CustomMiddleware_class',
]
- Please remember to add the middleware at an appropriate position, since the evaluation of middleware is position-dependent.
Things to remember when using middleware
- Order of middleware is important.
- A middleware may implement
process_request
but may not implementprocess_response
andprocess_view
Conclusion
- Custom middleware should be used when you want to implement certain code for every request or response or both.
- Write Django Custom middleware only when you have unique requirements in production since it would mean additional overhead to the request-response cycle which at certain times can put a negative effect.
Thanks for reading. If you found the article useful don’t forget to clap and do share it with your friends and colleagues. If you have any questions, feel free to reach out to me. Connect with me on 👉 LinkedIn, Github :)