DRF 限制
DRF 限制
限制某个用户访问某个接口的频率
DRF 提供的限制方案
- AnonRateThrottle,限制匿名用户的访问频率
- UserRateThrottle,限制认证用户的访问频率
- ScopedRateThrottle,限制访问特定API的频率
自定义限制方案
自定义限制类
限制10s内只能访问3次
visit_record = {}
class MyRateThrottle(object):
"""限制10s内只能访问3次"""
def __init__(self):
self.history = None
def allow_request(self, request, view):
ip = request.META.get('REMOTE_ADDR')
timestamp = time.time()
if ip in visit_record:
self.history = visit_record[ip]
while self.history.__len__() != 0:
if timestamp - self.history[-1] > 10:
self.history.pop()
else:
break
if self.history.__len__() < 3 and self.history[-1] + 10 > timestamp:
self.history.insert(0, timestamp)
return True
else:
return False
else:
self.history = [timestamp, ]
visit_record[ip] = self.history
return True
def wait(self):
"""多长过后可以访问"""
return self.history[-1] + 10 - time.time()
全局配置
settings.py
REST_FRAMEWORK = {
...
"DEFAULT_THROTTLE_CLASSES": ["auth_app.utils.MyRateThrottle", ],
}
局部配置
class TestView(APIView):
"""test view"""
throttle_classes = [MyRateThrottle, ]
def get(self, request):
return Response('test view')
使用内置类
class MyRateThrottle2(SimpleRateThrottle):
scope = 'test2'
def get_cache_key(self, request, view):
return self.get_ident(request)
REST_FRAMEWORK = {
...
"DEFAULT_THROTTLE_CLASSES": ["auth_app.utils.MyRateThrottle2", ],
"DEFAULT_THROTTLE_RATES": {
"test2": "18/m",
}
}
源码分析
请求 ——》urls.py ——》as_view ——》APIView的dispatch方法——》执行 self.initial(request, *args, **kwargs)
——》执行self.check_throttles(request)
获取访问限制类
获取访问限制类
判断有没有被限制,如被限制执行 throttle.wait() ,返回还需多少s才能访问