程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Django middleware and its programming

編輯:Python

List of articles

      • brief introduction
      • Customize Django middleware

Django One function is middleware , He can do this without changing the existing code , Add some additional operations to the request or corresponding etc , The most commonly used functions include login verification 、 Filter list 、 Logging and other scenarios .

brief introduction

In essence, it is a hook hook , stay request Coming or response It will trigger when passing , Modify according to the corresponding rules .

If you look at Django Project settings.py, You can see that there is always MIDDLEWARE There are some middleware currently used registered , As shown below

  • django.middleware.security.SecurityMiddleware: Some security protection mechanisms
  • django.middleware.common.CommonMiddleware: Provide for the right to URL Rewriting of , be based on APPEND_SLASH and PREPEND_WWW, If the former is True, If a has no trailing slash URL If there is no match, it will automatically add a slash to re match ; If the latter is True, If one doesn't www. At the beginning URL There is no match for , It will automatically add a www. Rematch
  • django.middleware.csrf.CsrfViewMiddleware: start-up CSRF protective , Will automatically add a... To the web page template returned to the front end csrf Hide controls ,value It's a randomly generated string , The form will be submitted with this token To the back end , The backend validates csrf token Is it legal , Avoid malicious forgery attacks
  • django.contrib.sessions.middleware.SessionMiddleware: start-up session function , You can use... In a project session
  • django.contrib.auth.middleware.AuthenticationMiddleware: Use sessions to associate users with requests

Django Middleware inherits from django.utils.deprecation.MiddlewareMixin Provides five ways to actually , At least one of these needs to be implemented

  • process_request(self,request):request Before the arrival of route matching , Normal return None; Exception return HttpResponse
  • process_view(self,request,callback,callback_args,callback_kwargs):callback It's a view function , Back args It's a position parameter , This is triggered before the view function is called after route matching , For code level replacement and filtering , Here you can get the parameters of the view function , Normal return None; Exception return HttpResponse
  • process_response(self,request,response): Triggered before the corresponding is sent from the server , Normal return None; Exception return HttpResponse
  • process_exception(self,request,exception): When an exception occurs, it will be called , Exception return HttpResponse
  • process_template_response(self,request,response): Attempt to complete function execution , Mainly render Method , Realized render Method . Normal return None; Exception return HttpResponse

If you normally go to the next step , All return to None Of , Just don't write the return value return

Customize Django middleware

For example, my current requirement is to add my own login verification function , I can actually do it through decorators , It can also be verified by being at the front of the code session, But I have more than one function that needs to do this , If you do this for all functions , It's going to be a lot of trouble , The role of middleware is highlighted , Only one middleware is required , He can manage all the function methods .

First create a app It's called middleware, Create a python file login.py, Create a class inside LoginMiddleware

from django.http import HttpResponse
from django.utils.deprecation import MiddlewareMixin
import re
class LoginMiddleware(MiddlewareMixin):
count_dict = {
} # Create a dictionary for counting times 
def process_request(self,request):
print(' This is my middleware ')
return

And then modify settings.py file , Modify as follows , Add middleware and app

INSTALLED_APPS = [
...
'middleware'
]
MIDDLEWARE = [
...
'middleware.login.LoginMiddleware',
]

Then start the service


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved