Django REST framework(DRF)提供了一个throttle_classes属性,可以用于限制API的访问频率。它可以防止恶意用户发送大量请求以消耗服务器资源。
使用throttle_classes属性,需要在settings.py中配置REST_FRAMEWORK:
REST_FRAMEWORK = {'DEFAULT_THROTTLE_CLASSES': ['rest_framework.throttling.AnonRateThrottle', # 匿名用户访问频率限制'rest_framework.throttling.UserRateThrottle', # 登录用户访问频率限制],'DEFAULT_THROTTLE_RATES': {'anon': '100/day', # 匿名用户每天最多100次请求'user': '1000/day', # 登录用户每天最多1000次请求}
}
这里使用了两个默认的限制类:AnonRateThrottle和UserRateThrottle。AnonRateThrottle用于限制匿名用户的访问频率,UserRateThrottle用于限制登录用户的访问频率。
在DEFAULT_THROTTLE_RATES中,我们可以为每个限制类指定一个速率限制,例如'anon': '100/day'表示每天匿名用户最多可以发送100个请求。
如果需要自定义限制类,可以继承throttling.SimpleRateThrottle类并实现allow_request()和get_cache_key()方法。例如:
from rest_framework.throttling import SimpleRateThrottleclassCustomThrottle(SimpleRateThrottle):rate = '10/hour'# 每小时最多10次请求def get_cache_key(self, request, view):return self.get_ident(request) # 使用IP地址作为缓存keydef allow_request(self, request, view):ifnot self.rate:return Trueself.key = self.get_cache_key(request, view)if self.key isNone:return Trueself.history = self.cache.get(self.key, [])self.now = self.timer()while self.history and self.history[-1] <= self.now - self.duration:self.history.pop()if len(self.history) >= self.num_requests:return Falseself.history.insert(0, self.now)self.cache.set(self.key, self.history, self.duration)return True
在上面的例子中,我们定义了一个名为CustomThrottle的限制类,它每小时最多允许10次请求。get_cache_key()方法返回一个缓存key,这里使用了请求的IP地址。allow_request()方法用于判断当前请求是否允许访问,如果超过了限制次数,则返回False,否则返回True。
然后在视图类中使用throttle_classes属性指定限制类即可:
from rest_framework.throttling import AnonRateThrottle
from myapp.throttling import CustomThrottle
classMyView(APIView):throttle_classes = [AnonRateThrottle, CustomThrottle]def get(self, request):# ...
在上面的例子中,我们指定了两个限制类:AnonRateThrottle和CustomThrottle,它们分别用于限制匿名用户和所有用户的访问频率。
上一篇:学习streamlit-5
下一篇:免费搭建个人博客