6:Django-DRF-节流(频率限制)
节流(频率限制)
为了控制用户对某个url请求的频率,比如,一分钟以内,只能访问三次,也可以加上限制,比如成为一个会员,发送频率就会增加
案例
局部使用
写一个类,继承自SimpleRateThrottle,(根据ip限制)
from rest_framework.throttling import SimpleRateThrottle
#重写get_cache_key,返回self.get_ident(request)
#一定要记住配置一个scop=字符串
class Throttle(SimpleRateThrottle):
scope = 'zyl'
def get_cache_key(self, request, view):
return self.get_ident(request)
根据user进行限制
class UserThrottle(SimpleRateThrottle):
scope = "LuffyUser"
def get_cache_key(self, request, view):
return request.user.username
在setting里配置:(一分钟访问三次)
REST_FRAMEWORK = {
'DEFAULT_THROTTLE_RATES':{
'zyl':'3/m'
}
}
在视图类里使用:
class Books(APIView):
throttle_classes = [Throttle,]
def get(self,request):
return Response('')
全局使用
setting中配置
'DEFAULT_THROTTLE_CLASSES':['自己定义的频率类'],
view:
局部禁用
throttle_classes = []
自定义频率类
根据ip限制思路
#(1)取出访问者ip
# (2)判断当前ip不在访问字典里,添加进去,并且直接返回True,表示第一次访问,在字典里,继续往下走
# (3)循环判断当前ip的列表,有值,并且当前时间减去列表的最后一个时间大于60s,把这种数据pop掉,这样列表中只有60s以内的访问时间,
# (4)判断,当列表小于3,说明一分钟以内访问不足三次,把当前时间插入到列表第一个位置,返回True,顺利通过
# (5)当大于等于3,说明一分钟内访问超过三次,返回False验证失败
class MyThrottle(BaseThrottle):
VISIT_RECORD = {}
def __init__(self):
self.history = None
def allow_request(self, request, view):
# 自定义控制每分钟访问多少次
# 取出访问者ip,request.META拿出ip
print(request.META)
# 拿到当前ip
ip = request.META.get('REMOTE_ADDR')
#拿到当前时间
import time
ctime = time.time()
#判断当前ip在不在访问字典里,添加进去并且直接返回True,表示第一个访问
if ip not in self.VISIT_RECORD:
#一开始肯定不在所以先放进去
self.VISIT_RECORD['ip'] = [ctime,]
return True
#这里的history是当前访问者ip对应的时间列表[第一次访问时间,]
self.history = self.VISIT_RECORD.get(ip)
# 循环判断当前ip的列表,有值,并且当前时间减去列表的最后一个时间大于60s,把这种数据pop掉,这样列表中只有60s以内的访问时间,
while self.history and ctime-self.history[-1] >60:
self.history.pop()
# 判断,当列表小于3,说明一分钟以内访问不足三次,把当前时间插入到列表第一个位置,返回True,顺利通过
if len(self.history) < 3:
self.history.insert(0,ctime)
return True
# 当大于等于3,说明一分钟内访问超过三次,返回False验证失败
else:
return False
def wait(self):
import time
ctime = time.time()
return 60 - (ctime - self.history[-1])
如果你想一分钟访问六次其七次,这样就写死了,所有提供了SimpleRateThrottle类,只要用里面的方法就可以了