Introduction to Django Middleware
The middleware has to pull every request and response to the web application and process the middleware’s processing over request and response. On a simple, these middleware components are nothing more than a Python class; these middleware elements are called components, and each of these components is responsible for performing some operation. The settings.py file represents these components as a Python list variable called MIDDLEWARE strings. You can declare the middleware components in any path within the application as long as you include the path in the Middleware tuple within the settings.py file. In this topic, we are going to learn about Django Middleware.
Include the middleware item in the MIDDLEWARE list within the settings.py file to activate a middleware. The list below holds the default middleware items generated when a Django project starts. The order of declaration for the middleware components has significance.
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',
The following explains the necessity and usage of the default middleware listed above in the Django framework:
|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||In 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 URLs 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 object, and session values can be inserted into this dictionary object using a 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 a currently logged-in user to every httpRequest object entered 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 of declaration for the middleware components is significant.
- 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 significant.
- The _init_ method is executed during the start of the server.
- the _call__ method is executed for every request.
Mandatory Methods in a Middleware
The middleware must include at least one of the methods listed below:
- 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 excellent flexibility to middleware services. So these custom-level middleware services play an important role in Django middleware setups. You can modulate the properties of built-in middleware services to achieve various middleware capabilities.
1. Place a file called middleware.py anywhere inside the project. The location where this middleware file has been placed is not a big deal, as per the Django setup. The crucial aspect is ensuring that this file’s path is accurately specified in the middleware list within 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; Ensuring the order of middleware execution is crucial; to achieve that, it is important to place the newly added middleware item as the last element in the middleware listing. It is also essential to ensure that the middleware item is strictly in string format.
class NewMiddleware: 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!!!") return request 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', # Userdefined Middleware 'Django_app1.middleware.NewMiddleware', ]
Based on the mentioned entry, we can conclude that the middleware.py file resides inside the Django_app1 folder. Inside the file is an instance of a middleware class named NewMiddleware. If there is a need to install multiple new middlewares in the middleware.py file, separate entries must be added.
3. Reload the server using the python manage.py runserver command and verify the webpage.
Once the server loads and receives any request from the page, it displays the message “The Newly installed middleware is successfully triggered!!!” on the screen. This proves the newly installed middleware is working as expected.
We hope that this EDUCBA information on “Django Middleware” was beneficial to you. You can view EDUCBA’s recommended articles for more information.