节流指的是控制访问频率,比如60s内最多访问3次
针对匿名用户的唯一标识是ip
针对注册用户的唯一标识是用户名
先看自定义的一个节流类:
VISIT_RECORD={} #访问记录
from rest_framework.throttling import BaseThrottle
class MyThrottling(BaseThrottle):
'''自定义访问控制类,同一ip60内最多访问3次'''
def __init__(self): #数据封装
self.history=None
def allow_request(self,request,view): #判断是否可以访问
remote_addr=request.META.get('REMOTE_ADDR') #获取访问ip,作为判断依据
'''remote_addr = request._request.META.get('REMOTE_ADDR') # 获取访问ip'''
ctime=time.time()
if remote_addr not in VISIT_RECORD:
VISIT_RECORD[remote_addr]=[ctime]
return True # 可以继续访问
# 返回False,不能再访问
history=VISIT_RECORD.get(remote_addr) #history是列表,字典里面没有返回None,不报错
self.history=history
while history and history[-1]<ctime-60: #清除无效记录数据
history.pop()
if len(history)<3:
history.insert(0,ctime)
return True
def wait(self): #返回还需要等多少秒
ctime=time.time()
return 60-ctime-self.history[-1]
用法和认证,权限相同
class Eg(APIView):
authentication_classes = [MyAuthenticate,] #使用自定义认证类
permission_classes = [MyPermission,] #局部使用自定义权限类
throttle_classes = [MyThrottling,] #局部使用自定义访问控制类
def get(self,request,*args,**kwargs):
print(request.user)
return HttpResponse("GET")
Restframework自带的有一些节流类,比如SimpleRateThrottle
就和上面自定义的节流类功能相同
用法:
from rest_framework.throttling import SimpleRateThrottle
class VisitThrottle(SimpleRateThrottle): #用自带的节流类实现和自定义节流类一样的功能
scope="arg" #随便写,和配置文件里对应上就行
def get_cache_key(self, request, view):
return self.get_ident(request) #获取ip
然后在配置文件中添加:
REST_FRAMEWORK = {
'DEFAULT_THROTTLE_RATES':{
"arg":'3/m', #表示一分钟3次,还有5/s ,45/h等等
}
}
####对登录用户已用户名作为限制条件
from rest_framework.throttling import SimpleRateThrottle
class VisitThrottle(SimpleRateThrottle): #用自带的节流类实现和自定义节流类一样的功能
scope="user" #随便写,和配置文件里对应上就行
def get_cache_key(self, request, view):
return self.request.user.username #通过认证获取到登录用户的用户名
然后在配置文件中添加:
REST_FRAMEWORK = {
'DEFAULT_THROTTLE_RATES':{
"arg":'3/m', #表示一分钟3次,还有5/s ,45/h等等
"user":'45/h',
}
}