Home > Backend Development > Python Tutorial > How to implement interceptors in Django middleware

How to implement interceptors in Django middleware

不言
Release: 2018-06-02 14:28:21
Original
3087 people have browsed it

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 response
Copy after login

Process 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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template