Detailed Explanation of Functions in Middleware in Django

  • 2021-07-22 10:12:54
  • OfStack

1 example of middleware


import time

from django.urls import reverse
from django.utils.deprecation import MiddlewareMixin


class TimeItMiddleware(MiddlewareMixin):
  def process_request(self, request):
    return

  def process_view(self, request, func, *args, **kwargs):
    if request.path != reverse('index'):
      return None

    start = time.time()
    response = func(request)
    costed = time.time() - start
    print('process view: {:.2f}s'.format(costed))
    return response

  def process_excepttion(self, request, exception):
    pass

  def process_template_response(self, request, response):
    return response

  def process_response(self, request, response):
    return response

The functions in middleware are:

process_request process_view process_tmplate_response process_response process_exception

The following are introduced separately:

process_request:

This is the first method when the request comes to middleware. This method can have two return values, HttpResnonse or None. If HttpResponse is returned, the next processing method will only execute process_response, and other methods will not be executed. It should be noted here that if your middleware is the first MIDDLEWARE configured by settings, the remaining middleware will not be executed; If None is returned, Diango will continue to execute other methods.

process_view:

This method is executed after the process_request method, with the parameters shown in the code above, where func is the view method we are going to execute. Therefore, if you want to count the execution time of 1 view, you can do it here. Its return value is like process_request 1, HttpResponse or None, and its logic is also like 1. If None is returned, Django will help you execute the view function to get the final response.

Process_template_response:

After executing the above method, and Django helps us execute view and get the final response, if response of template is used (this refers to response returned by return render (request, 'index. html', context = {})), it will come to this method. In this method, we can do one operation on response, such as Content-Type setting, or other modifications/additions to header.

process_response:

When all the processes are processed, this method comes. The logic of this method is exactly the same as that of process_template_response, except that the latter is for the processing of response with templates.

process_exception:

The above processing methods are introduced in sequence, but this method is not very similar. This method is entered only when an exception occurs. At what stage did the anomaly occur?

It can be simply understood as an exception in the View to be called (that is, in the func function of process_view) or an exception in the rendering of the returned template response. However, it should be noted that if you manually call func in process_view, as we did above, process_exception will not be triggered. After receiving the exception, this method can choose to handle the exception and then return an HttpResponse with exception information, or directly return None without handling it. In this case, Django will use its own exception template.

The above excerpt is from "Django Enterprise Development Practical Combat" written by Hu Yang.


Related articles: