Home > Article > Backend Development > How to implement interceptors in Django middleware
This article mainly introduces the method of implementing interceptors in Django middleware. It has certain reference value. Now I share it with you. Friends in need can refer to it
1. Preface
We are all familiar with the interceptor of JavaWeb Struts2. Before the request is handed over to Action for processing, it is processed in the interceptor first, and then handed over to Action after processing.
How to achieve the same effect in Django?
2.Django middleware
This is the directory structure of my project.
First, create a new file named middleware.py
## in the app directory (that is, the web directory of my project)
#Add the following code inside:try: from django.utils.deprecation import MiddlewareMixin # Django 1.10.x except ImportError: MiddlewareMixin = object # Django 1.4.x - Django 1.9.x class SimpleMiddleware(MiddlewareMixin): def process_request(self, request): return None def process_response(self, request, response): return responseProcess the request in process_request and process_response to process the response. In the process_request method, when the return value is an object of type HttpResponse, it is not handed over to the ordinary controller for processing, but is returned directly to the browser. When the return value is None, the request is handed over to the ordinary controller after processing. controller processing. In the middleware configuration of the settings.py file, we just created the middleware. At this point, the work configuration of using middleware to do the interceptor is completed. Related recommendations:
How to directly return the request from Django’s middleware
The above is the detailed content of How to implement interceptors in Django middleware. For more information, please follow other related articles on the PHP Chinese website!