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

Note: Django rest framework access frequency

編輯:Python

First, customize a class of access frequency , Then you can quote it in the attempt , as follows :

1, First define the class of access frequency , The following code : No inheritance restframework Any class

# Here is the code of access frequency , No inheritance 
# This code is based on the accessed IP Address To restrict access .... Similarly, it can be used to restrict access according to the user name of access .
# A dictionary is defined here , Used to record access frequency , Of this dictionary key Namely ip Address ,value That is, the time record value of access is value, You can use a dictionary here , You can also flip to cache , You can also turn to the database 
VISIT_RECORD = {
}
import time
from rest_framework.throttling import BaseThrottle
class VisitThrottle(object):
def __init__(self):
self.history = None
# 60 Can only access... In seconds 3 Time 
def allow_request(self, request, view):
#return True Indicates that access can continue 
#return False Indicates that the frequency of access is too high , Limited 
#1, Get the user's ip Address 
remote_addr = request.META.get ('REMOTE_ADDR')
# Judge ip Is here or not VISIT_RECORD Inside , Then add the time 
ctime = time.time()
# Below if Statement is the setting of the first access 
if remote_addr not in VISIT_RECORD:
VISIT_RECORD[remote_addr] = [ctime,]
return True
history = VISIT_RECORD.get(remote_addr) # Definition history Historical record , Here get the specified ip Access list of addresses 
self.history = history # Assign this value to the variable of the whole class , Then you can give it to the following wait() The function uses 
# Next, define a cycle , Use it to compare the current time and history Compare the time inside , Because consider using the list POP operation , So here we insert time from the front , The latest time is on the left , The farthest time is on the right 
while history and history[-1] < ctime-60: # Because in one minute , So it's minus 60
history.pop() # If the rightmost time is less than the current time minus 60, Then perform pop operation , Clear the time on the far right , Here we can compare circularly , Until the list is cleared .
# Now let's begin our visit history Limit the number of , If it is less than 3 We go back to True , Indicates that access can continue 
if len(history) < 3:
history.insert(0, ctime)# Insert the current time into 0 A place 
return True
def wait(self):
# return Return value , Return several , You will be prompted on the page how many seconds are left to continue accessing , For example, we write return 10 Said with 10s You can continue to visit 
# You can customize the dynamic time , Then return , Then it will dynamically prompt how many seconds left to return 
ctime = time.time()
left_time = 60-(ctime-self.history[-1])
return left_time

2, In the attempt is to use :

class AuthView(APIView):
''' For user login Here you can get the user name and password sent by the front desk , Then go to the database to verify , At the same time, we also generated token, Then it returns to the user token, It is used for sending requests after users , It has to be Take this with you token Request . '''
# authentication_classes = [] # Here, because the validation class is set in the global , So leave this list blank , So that this view can not be verified globally , Direct execution .
# Class list setting of access frequency 
throttle_classes = [VisitThrottle,]
def get(self, request, *args, **kwargs):
return HttpResponse('hello workd')
def post(self, request, *args, **kwargs):
ret = {
'code':1000, 'msg':None}
try:
user = request._request.POST.get('username')
password = request._request.POST.get('password')
obj = models.UserInfo.objects.filter(username=user, password=password).first()
if not obj:
ret['code'] = 1001
ret['msg'] = ' Wrong username or password '
# Not logged in user created token, Use the definition of md5() Function to generate token
token = md5(user)
# Save the gold database , Update if you have , Create without , Because you can only use the latest token, So you need to update .
models.UserToken.objects.update_or_create(user=obj, defaults={
'token':token})
# You need to return to the user token
ret['token'] = token
except Exception as e:
ret['code']=1002
ret['msg']=' Request exception '
return JsonResponse(ret)

3, You can also configure in the global


REST_FRAMEWORK = {

# 'DEFAULT_AUTHENTICATION_CLASSES':['api.utils.auth.FirstAuthenticate',], # Note this format , there DEFAULT_AUTHENTICATION_CLASSES yes restframework Configure the specified , The following list is the certified classes . The path of the authentication class is written inside 
# The following two sentences are the settings of anonymous users :
'UNAUTHENTICATED_USER':None, # anonymous , be request.user = None
'UNAUTHENTICATED_TOKEN':None, # anonymous , be request.token = None
# 'DEFAULT_PERMISSION_CLASSES':['api.utils.permission.MyPermission'],
'DEFAULT_THROTTLE_CLASSES': ['api.utils.throttle.MyThrottle']
}

The definition is inherited from SimpleRateThrottle() class

1, Settings in this class

2, views.py Code in file , Inherited code , as follows :

# The following is inherited from SimpleRateThrottle The realization of the class , His class , It has already helped us to realize based on IP Access frequency control , Just set some parameters after inheritance 
from rest_framework.throttling import BaseThrottle, SimpleRateThrottle
class VisitThrottle1(SimpleRateThrottle):
# scope = 'lxbai' # This is a custom , This scope Used to set the access frequency key Of , After this setting , It needs to be in settings.py It defines , If it's not written here scope, Write only the following rate It is good , It is specially used to control this class .
rate = '10/m' # This reference source code , Set up 60 second 10 Time .
# Rewrite the function that needs to be rewritten 
# hold cache_key Set to id, That's what ip Set the address to key, then history Set to value
def get_cache_key(self, request, view):
return self.get_ident(request)

explain 1: If set here scope After that , You don't need to set it here rate 了 , It needs to be in settings.py In the definition of , as follows :

REST_FRAMEWORK = {

'DEFAULT_THROTTLE_RATES':{

'lxbai': '10/m' # This scope lxbai We defined it in that inheritance class .
}
}

explain 2: If it is not set in this scope, Just use that rate Set to rate='10/m’ That's all right. , It's also a one minute visit 10 Time .

summary : There are many settings in this section , When it's done , Refer to the original video and source code .


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