1 频率组件
![]()
#自定义组件写频率认证(重点继承BaseThrottle)
from rest_framework.throttling import BaseThrottle
import time
class Thro(BaseThrottle):
dic={}
def allow_request(self, request, view):
'''
:param request:
:param view:
:return: 布尔类型
'''
ctime=time.time()
self.ip=request.META.get('REMOTE_ADDR')
if self.ip and self.ip not in self.dic:
self.dic[self.ip]=[ctime]
return True
lis=self.dic.get(self.ip)
#把最早的时间和现在时间对比 1.大于多少秒(60s)的去掉 2.留下的是多少秒内(60秒内)的时间数 = 访问次数
while lis and ctime-lis[-1]>60:
lis.pop()
#剩下的时间列表 1.在多少秒内(60s内)2.设置访问次数:列表内时间个数=限制范文次数
if len(lis)<6:
lis[:0]=[ctime]
print (self.dic)
return True
print(self.dic)
return False
#访问超过限制触发
def wait(self):
'''
:return:多少秒过后才可以访问
'''
#最早的时间
tim=self.dic.get(self.ip)[-1]
ctime=time.time()
#ctime-tim 值越来越大
return 60-(ctime-tim)
#局部使用
throttle_classes=[Thro,]
#全局使用
REST_FRAMEWORK = {
'DEFAULT_THROTTLE_CLASSES': ['app01.Mythrottle.Thro', ],
}
自定义的频率组件