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

Using AOP Middleware in Django

編輯:Python

What is the AOP?

  • AOP, Section oriented programming , It can be realized by precompiling and runtime dynamic agent to add functions to the program dynamically and uniformly without modifying the source code
  • utilize AOP Parts of the business logic can be isolated , Thus the degree of coupling between the parts of the business logic is reduced , Improve program reusability , At the same time improved the efficiency of development .
  • The main functions are : logging , Performance statistics , safety control , Transaction processing , Exception handling and so on .

AOP It is to extract the facets in the business processing process , What it faces is the A step or stage

What is middleware ?

  • middleware Is the extra processing between the goal and the result , stay Django The middle is request and response Between , It is relatively simple to implement , But note that it is globally valid , Input and output results can be changed globally
  • The main functions are : Login authentication 、 Traffic statistics 、 Malicious request interception, etc

How to be in Django Custom Middleware in ?

These are django Built in default middleware

MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

We first create a project named... Under the project directory middleware Folder , Then create a python file , Here I put python The file is named learnmiddle

from django.utils.deprecation import MiddlewareMixin
class HelloMiddle(MiddlewareMixin):
pass

This is the basic code style , And then with these, in settings.py Self contained MIDDLEWARE Add a statement to the list :

'middleware.learnmiddle.HelloMiddle',

Inherit this from MiddlewareMixin Class registration of
django Built in five pointcut interfaces :

  1. process_request:
    In execution Before the view function Called , You can return without taking the initiative HttpResponse object
def process_request(self, request):
pass
  1. process_views:
    In execution Before the view function Called , You can return without taking the initiative HttpResponse object
def process_views(self,request,view_func,view_args,view_kwargs):
pass
  1. process_template_response:
    stay The view function just finished executing After the call , Must return response, And only when the view function has render Method is called
def process_template_response(self,request,response)
pass
  1. process_response:
    all Before the response returns to the browser call , Must return response
def process_response(self,request,response)
pass
  1. process_exception
    When the view function throws an exception call , You can return without taking the initiative HttpResponse object

The most common of these five tangents is process_request and process_exception

  • We can use process_request Realization : Statistical function 、 Black and white list 、 The crawler 、 Limit access frequency
  1. Statistical function
    We can use the statistics function to record some information about users , And then we analyze the data , Make better use of the market
    The following code directly prints out the user's host address
print(request.META.get('REMOTE_ADDR'))
  1. Black and white list function
    Some shopping websites can evaluate the credit rating of users based on their actions on the website , In some Raffles , Set the winning probability for users , Of course, we can write this function on the view function , But this will reduce the coupling of view functions , Reduce code readability , The following code indicates that the user at a certain address cannot scramble for tickets
if request.path == '/getticket/':
if ip.startswith('127.0.0.1'):
return HttpResponse(' Have robbed away ')

This is the custom middleware process_request The code in

def getticket(request):
return HttpResponse(' Coupons and ')

This is the code in the view function

  • It can be seen that : When ordinary users log in to the abstract page, they see ‘ Coupons and ’


And then 127.0.0.1 Users at the beginning can only see that they have been robbed

  1. Anti crawler function

Some users will crawl the browser , If a user frequently refreshes and crawls data to the server , Then the consumption of our server resources will be huge , It is not conducive to the long-term use of our server , The following code shows that the user can only search the browser once in ten seconds

if request.path == '/fanpa/':
result = cache.get('ip')
if result:
return HttpResponse(' You visit too often ')
cache.set('ip',ip,timeout=10)

This is the custom middleware process_request The code in

def fanpa(request):
return HttpResponse(' Search successful ')

This is the code in the view function

  • You can see , If we operate normally , No more requests to the server in ten seconds , So what we see is ‘ Search successful ’ The words... , If we send a request to the server more than once in ten seconds , That is, set the cache expiration time to 10 seconds , If the cache exists when the request is sent , Then we'll see ‘ You visit too often ’ The word "ground"
  1. Limit access frequency

Some users will perform malicious operations on the browser , Frequent browser refresh is a heavy burden on the server , We need to limit the frequency of access , The following code shows that the user can only access it ten times in 60 seconds , If more than ten times, you have to wait for a certain period of time to operate , If more than thirty times , Let's talk about users pulling into the blacklist , It is forbidden for one day

#get A blacklist cache , If it exists, get , If it doesn't exist, create a new one [] An empty list 
black_list = cache.get('black', [])
# If the user ip On the blacklist , Then return to 
if ip in black_list:
return HttpResponse(' The blacklist ')
''' Here we create a request sequence [] Each access generates a cache with a duration of 60 Second time stamp , Put the timestamp at the beginning of the sequence If the time interval between the first timestamp and the last timestamp is greater than 60 second We'll throw the last one away , Otherwise, we'll put the timestamp in the front Ask to appear in this named requests The length of the sequence of If the length is greater than 10, The number of return requests is too frequent If the length is greater than 30, Pull into the blacklist '''
requests = cache.get('ip', []) #cache.get( Parameter one , Parameter two ), When parameter one does not exist, parameter two is returned 
while requests and time.time() - requests[-1] > 60:
requests.pop() # Throw away the tail data 
# Insert requests The value of the sequence is a time stamp 
requests.insert(0, time.time()) # Insert values forward 
cache.set('ip', requests, timeout=60)
if len(requests) > 30:
black_list.append(ip)
cache.set('black',black_list,timeout=60*60*24) # Get into , The blacklist is closed for one day 
return HttpResponse(' Sealed for one day ')
if len(requests) > 10:
return HttpResponse(' Too many requests ')
  • We can use process_exception When the server throws an exception , The client will not directly report an error , So that some functions can still be used normally
    Sometimes we don't want users to see some error reporting pages , We can intercept it when an error is reported , Return to a normal page
def process_exception(self,request,exception):
return redirect(reverse('shouye'))

This code means to return to the home page directly when an exception occurs


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