Introduction to Django Middleware
The middleware has to pull every request and response to the web application and process the middleware’s processing over the request and response. On simple these middleware components are nothing more than a python class; these middleware elements are called as components; each of these components is responsible for performing some operation. These components are represented as the string’s in the python list variable MIDDLEWARE in the settings.py file. The middleware components can be declared in any of the paths in the application, Only thing to be ensured is whether that path is declared in the Middleware tuple in the settings.py file. In this topic, we are going to learn about Django Middleware.
A middleware can be activated by mentioning the middleware item in the MIDDLEWARE list in the settings.py file. The below-mentioned list holds the default list of middleware items that get generated when a Django project started. The order in which the middleware components are declared is very important.
MIDDLEWARE = [
The necessity and usage of the above-listed default middlewares in the Django framework are explained below,
|djangosecure.middleware.SecurityMiddleware||X-Frame-Options: DENY||Limits the pages displayed to be within a frame.|
|HTTP Strict Transport Security||Setting this allows the website to be accessible to the browser only on HTTPS instead of HTTP.|
|X-Content-Type-Options: nosniff||This option helps to prevent against MIME sniffing vulnerabilities.|
|X-XSS-Protection: 1; mode=block||When an XSS(Cross-site scripting) attack is detected, it stops the website pages from getting further loaded.|
|SSL Redirect||This will redirect all the http connections to https connections.|
|Detecting proxied SSL||At rare instances, the request.is_secure() the method returns false for valid requests; setting this option will help to set an alternative header to the secured external connection.|
|django.middleware.common.CommonMiddleware||Rewriting of URL’s based on APPEND_SLASH and PREPEND_WWW settings. When APPEND_SLASH is TRUE, and the URL does not have a ‘/,’ then the new url will have a slash at the end of the URL.||NA|
|Restrict access for the users listed in DISALLOWED_USER_AGENTS setting|
|django.contrib.sessions.middleware.SessionMiddleware||When the session Middleware is activated, every HttpRequest object will have a session attribute tagged as the first argument. This is a dictionary kind of object, and session values can be inserted into this dictionary object using request. Session anywhere in the view file.|
|django.middleware.csrf.CsrfViewMiddleware||This middleware option allows protection against all cross-site request forgeries.|
|django.contrib.auth.middleware.AuthenticationMiddleware||Setting this middleware option adds currently logged-in user to every httpRequest object which is entering in.|
|django.contrib.messages.middleware.MessageMiddleware||This middleware will handle all temporary messages between the website and the web browser.|
|django.middleware.clickjacking.XFrameOptionsMiddleware||Limits the pages displayed to be within a frame.|
How does Middleware work in Django?
Below are the key points on the working of middleware in Django,
- The order in which the middleware components are declared is very important.
- The middleware classes get executed twice in the request/response lifecycle.
- During a request, the classes are executed from top to bottom order.
- During a response, these classes get executed from bottom to top order. this is why the order of the components is very important.
- The _init_ method is executed during the start of the server.
- the _call__ method is executed for every request.
Mandatory Methods in a Middleware
At least one among the below-listed methods must be declared as a part of the middleware,
- If middleware needs to process during request:
- process_view(request, view_func, view_args, view_kwargs)
- If middleware needs to process during response:
- process_exception(request, exception) (only if the view raised an exception)
- process_template_response(request, response) (only for template responses)
- process_response(request, response)
For setting up a custom middleware setup in place, the below-mentioned steps are expected to be followed; This custom middleware will be a user-defined middleware staying in the middle and doing the needed or guided set of processing on the passed request and response messages. Custom middleware offers great flexibility to middleware services. So these custom-level middleware services play a very important role in Django middleware setups. Additionally, the properties of built-in middleware services can also be modulated to several possible extents to attain middleware capabilities.
1. Place a file called middleware.py anywhere inside the project. The location at which this middleware file has been placed is not a big deal as per the Django setup. What matters is the process of ensuring the path placed for this file is precisely mentioned in the middleware list in the settings.py file. This is the most important element.
2. Place the class for the middleware inside the middleware.py file. This is the most important step in this process; Since the order in which the middleware gets executed is a great deal, it is important to ensure that the newly added middleware item is placed as the last element in the middleware listing. Also, it needs to be strictly ensured that the middleware item is of string format,
def __init__(self, get_request):
self.get_request = get_request
def __call__(self, request):
request = self.get_request(request)
print("The Newly installed middleware is successfully triggered!!!")
# Userdefined Middleware
From the above-mentioned entry, it could be decided that the middleware.py file is placed inside the Django_app1 folder, and the file has a middleware class named NewMiddleware inside it as an instance. If several more new middlewares have to be installed in the middleware.py file, then separate entries for all those have to be placed.
3. Reload the server using the python manage.py runserver command and verify the webpage.
Once the server is loaded and any request is received from the page, the middle message mentioning “The Newly installed middleware is successfully triggered!!!” is displayed on the screen. This proves the newly installed middleware is working as expected.
This is a guide to Django Middleware. Here we discuss the All major concepts in middleware setups are explained in a very precise manner in the above-formulated article with necessary examples. You may also have a look at the following articles to learn more –