2、具体限制访问
对于匿名用户和认证用户做不同的限制访问
from rest_framework.throttling import BaseThrottle,SimpleRateThrottle class VisitThrottle(SimpleRateThrottle): scope = "anonymous" def get_cache_key(self, request, view): return self.get_ident(request) class UserThrottle(SimpleRateThrottle): scope = "user" def get_cache_key(self, request, view): return request.user.username3、配置限流类
可以再
setting.py文件中全局配置,也可以再视图中重写,局部配置,但是访问频率,需要限流类的scope属性定义。
对于匿名用户,每分钟访问5次,认证用户,每分钟5次REST_FRAMEWORK = { "DEFAULT_THROTTLE_CLASSES":["api.utils.throttle.UserThrottle"], "DEFAULT_THROTTLE_RATES":{ "anonymous":'5/m', "user":'10/m', } }4、视图
from rest_framework.views import APIView class UserInfoView(APIView): authentication_classes = [] permission_classes = [] throttle_classes = [throttle.VisitThrottle] # 标识匿名用户访问 def get(self, request, *args, **kwargs): print(request.META.get('REMOTE_ADDR')) # 这里可以获取到访问的IP return HttpResponse('访问成功')5、请求测试
使用postman或者浏览器发送请求
一分钟连续发送5次,正常
发送第6次时,访问受限
三、源码分析
像
django rest framework之 认证一样进入,request的请求流程,进入源码查看具体权限的操作1、进入dispath()方法

2、进入initial()方法

3、进入check_throttles()方法

4、获取限流类

获取限流类之后并实例化成对象,使得可以调用具体的方法

同样的默认的是通过全局配置

5、原生的限流类
在
rest framework中也有相应的限流类,主要使用SimpleRateThrottle,因为在SimpleRateThrottle中的一些方法已经是实现了我们需要的逻辑
来看一下SimpleRateThrottle具体做了什么
class SimpleRateThrottle(BaseThrottle): cache = default_cache # default_cache其实是缓存的一个对象 timer = time.time cache_format = 'throttle_%(scope)s_%(ident)s' scope = None THROTTLE_RATES = api_settings.DEFAULT_THROTTLE_RATES def __init__(self): if not getattr(self, 'rate', None): self.rate = self.get_rate() self.num_requests,
