The middleware

This is the 10th day of my participation in the August More Text Challenge. For details, see:August is more challenging

Djangos middleware is a frame-level hook that handles Djangos requests and responses globally

The request-handling and frame-level hooks in Django are essentially a class that defines five methods that are executed at specific times.

1. Create the middleware process

1. Create a new folder under app, Middlewares 2. In the folder, define the middleware class My_Middlewares. Py 3. When writing middleware, be sure to inherit MiddlewareMixinCopy the code
from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import HttpResponse
​
class MD1(MiddlewareMixin) :
    def process_request(self,request) :
        print(id(request))
        print("MD1 request")
        return HttpResponse("If the intermediate key has a return value in it, the following view function is not executed, even the one after the intermediate key.")
    
Copy the code
4. Register for MIDDLEWARE in settings.py to define MIDDLEWARE (! The middleware executes from top to bottom, from bottom to top)Copy the code
MIDDLEWARE = [
    'app.Middlewares.My_Middlewares.MD1'.# 'app.Middlewares.My_Middlewares.MD2',
]
Copy the code

2. Five methods and four characteristics of middleware

Execution time, execution order, parameters, and return value

2.1 Process_request (before the request)

Process_request (self, request) # process_request(self, request) # process_request(self, request) # Process_request (self, request) # None Normal flow HttpResponse (which has a return value) does not execute the following view function and route matching, and does not execute the following intermediate key. It is returned to the browser and directly executes the middleware's 'process_response' methodCopy the code

2.2 process_response

Process_response (self, request, response) # is used to respond to the request Request and view function are the same object. Response Response object return value: HttpResponse must returnCopy the code

2.3 process_view

Process_view (self,request,view_func,view_args,view_kwargs) The process_view method is an argument that is executed after process_request and before the view function: Request Request object and view function are the same object view_func view function view_args view function position argument () tuple view_kwargs view function keyword argument {} dictionary return value: None Indicates normal flow. The original view function is HttpResponse 1. If process_response is return Response, the process_view method of the middleware is returned, and neither view function performs 2. If process_response is return HttpResponse, execute the process_response method of the last middlewareCopy the code

2.4 process_exception

Process_exception (self, request, exception) # Process_exception (self, request, exception) # Process_exception (self, request, exception) Request The requested object and the view function are the same object. None The current middleware does not handle the exception, pass it to the next middleware handler. If neither of them handles the exception, then native Django handles the exception. HttpResponse The current middleware handles the exception, and the later middleware process_Exception does not execute. Execute the process_response method of the last middlewareCopy the code

2.5 process_template_response

Process_template_response (self, request, response) # process_template_response(self, request, response) Request and view functions are the same object. Response returns the TemplateResponse object value: Response. template_name Response. context_dataCopy the code

Pay attention to

Process_template_response is executed immediately after the view function completes, but it assumes that the object returned by the view function has a render() method (or indicates that the object is a TemplateResponse object or its equivalent).

3. Example of custom middleware

from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import HttpResponse
​
​
class MD1(MiddlewareMixin) :
    def process_request(self, request) :
        print("MD1 process_request")
        # ret = HttpResponse(" if the intermediate key has a return value, the view function will not be executed, even if the intermediate key has a return value ")
        # # return HttpResponse(" if the intermediate key has a return value, then the view function will not be executed, even if the intermediate key has a return value ")
        # return ret
​
    def process_response(self, request, response) :
        print("MD1 process_response")
        return response
​
    def process_view(self, request, view_func, view_args, view_kwargs) :
        # print(request) # 
      
        # print(view_func) # 
      
        # print(view_args) # ('1',)
        # print(view_kwargs) # {'id': '2'}
        print("MD1 process_view")
        # return HttpResponse("MD1 process_view")
​
    def process_exception(self,request,exception) : The views function is executed only when there is an exception
        print("Abnormal")
​
    def process_template_response(self,request,response) :
        print("MD1 process_template_response")
        return response
Copy the code

The view function

from django.shortcuts import render, HttpResponse
from django.template.response import TemplateResponse
​
# Create your views here.def index(request,*args,**kwargs) :
    print("index")
    # return render(request,"index.html",{"user":"abcdefg"})
    return TemplateResponse(request,"index.html", {"user":"abcdefg"})
Copy the code
Attached: Django request flow chart