官方文档:https://www.django-rest-framework.org/api-guide/throttling/
1、什么场景下需要限制访问频次呢?
1)防爬虫:爬虫可能会在短时间内大量的访问服务接口,增加服务器压力
2)对于需要限制访问频次的接口
2、DRF如何限速:
通过 rest_framework下面的throttling 模块实现
throttling模块主要提供了三种限速方式:
1)AnonRateThrottle
针对未登录用户的限速,通过IP地址区分用户
2)UserRateThrottle:
针对已登录用户,通过user id来区分用户
3)ScopedRateThrottle:
限制用于对于每个视图的访问频次,通过ip地址或者useid来区分
使用方法:
1)在配置文件中配置需要使用什么类型的限速,以及限制的访问频次
访问频次单位有:second,minute,hour和day
2)在对应的视图函数中使用
throttle_classes = (AnonRateThrottle,)
from rest_framework.throttling import AnonRateThrottle class GoodListView(APIView): throttle_classes = (AnonRateThrottle,) @cache_response(cache_errors=False) def get(self, request, format=None): print(request.query_params) goods = Goods.objects.all()[:10] goods_serializer = GoodListSerializer1(goods, many=True) return Response(goods_serializer.data)
3)使用装饰器
@throttle_class([AnonRateThrottle,])
from rest_framework.decorators import throttle_classes @throttle_classes([AnonRateThrottle,]) class GoodListView(APIView): # throttle_classes = (AnonRateThrottle,) @cache_response(cache_errors=False) def get(self, request, format=None): print(request.query_params) goods = Goods.objects.all()[:10] goods_serializer = GoodListSerializer1(goods, many=True) return Response(goods_serializer.data)
4)对于ScopedRateThrottle,可用于限制访问指定的API,仅当访问的视同中包含 throttle_scope属性时,才会应用此限制
class ContactListView(APIView): throttle_scope = 'contacts' pass class ContactDetailView(APIView): throttle_scope = 'contacts' pass class UploadView(APIView): throttle_scope = 'uploads' pass
然后在settings中配置如下:
REST_FRAMEWORK = { 'DEFAULT_THROTTLE_CLASSES': ( 'rest_framework.throttling.ScopedRateThrottle', ), 'DEFAULT_THROTTLE_RATES': { 'contacts': '1000/day', 'uploads': '20/day' } }
在上面的视图中,ContactListView和ContactDetailView两个视图中,throttle_scope都是contacts,settings中,设置的contacts频率限制为1000次每天,所以ContactListView和ContactDetailView两个视图函数加起来一天的访问次数不能超过1000次
UploadView的访问次数,不能超过20次每天