What Is Middleware In Django ?
Common Question for Python Django Developer Interviews ? Actually what is Middleware ? What is Role ? How many middleware are there ? can we write own middlewares in a application if yes tell me how ?
Haaahha Now you also Confused how to answer these questions ? , when i enter to interview panel i sucked lot of times , i make it my own ways ..
These are the questions commonly asking for the Interviews , Middleware have main role in our django application so only they asking these questions to everyone. Here I 'm telling you how you can easily tackle with these questions.
What is Middleware ?
Middleware is a Middleware is a ................, Dont worry i will help you out , Middleware is a framework of hooks into Django’s request/response processing. It’s a light, low-level “plugin” system for globally altering Django’s input or output. Each middleware component is responsible for doing some specific function.
What are the Common Middleware Classes in Django ?
MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', )
if you need more details about the each of the middleware classes please follow the link
How to Write Own Middlewares in our project ?
Step 1 :
if you don't have it you need to create the middleware folder within your app following the Structre.
Important : Don't forget to create the __init__.py empty file inside the middleware folder so your app recognize this folder.
Step 2 :
Now we should create a file for our custon middleware, in this blog let's suppose we want a middleware that filter users based on their IP. we create file called filter_ip_middleware.py the middleware folder with this code
Step 3 :
Add the midleware in your 'settings.py' .
We need to look for the MIDDLEWARE_CLASSES inside the settings.py and there we need to add our middleware( Add it in the last position ) . It should be like.
Step 4 :
DONE ! Now every request from the every client will call your custom middleware and process your
custom code. !