自定义频率类
如果重写频率限制的key的话,继承SimpleRateThrottle即可,
根据地址限制登录频率
class DingScopeThrottle(SimpleRateThrottle):
scope = 'user_ip'
def get_cache_key(self, request, view):
print(self.scope)
# print(request.Meta)
print(request._request.META)
# print(request._request.META.get('REMOTE_ADDR'))
# return self.
return request._request.META.get('REMOTE_ADDR')
settings类
'DEFAULT_THROTTLE_RATES': {
'user_ip': '3/m',
'anon': None,
}
如果重新频率逻辑,需要继承BASE重写2个方法
1. 判断师傅限次,没有限次可以请求true, 限次了不可以请求False
def allow_request(self, request, view):
"""
Return `True` if the request should be allowed, `False` otherwise.
"""
raise NotImplementedError('.allow_request() must be overridden')
2. 限次后调用,显示还需等待多长时间才能再访问,返回等待时间seconds
def wait(self):
"""
Optionally, return a recommended number of seconds to wait before
the next request.
"""
return None
class CustomThrottle(BaseThrottle):
allow_port = {}
def __init__(self):
self.history_list=[]
def allow_request(self, request, view):
"""
Return `True` if the request should be allowed, `False` otherwise.
"""
# raise NotImplementedError('.allow_request() must be overridden')
ip=request.META.get('REMOTE_ADDR')
if ip not in self.allow_port:
self.allow_port[ip]=[time.time()]
return True
self.history_list=self.allow_port.get(ip)
while True:
if (time.time() -self.history_list[-1])>60:
self.history_list.pop()
else:
break
if len(self.history_list)<3:
self.history_list.append(time.time())
return True
else:
return False
内置频率限制
AnonRateThrottle 限制所有匿名非认证用户,使用ip区分用户
UserRateThrottle 限制认证用户,使用user——id 来区分
ScopedRateThrottle 限制用户对位每一个视图的访问频次 使用ip或者user_id