官方文档:https://www.django-rest-framework.org/api-guide/throttling/django
一、什么场景下须要限制访问频次呢?api
1)防爬虫:爬虫可能会在短期内大量的访问服务接口,增长服务器压力服务器
2)对于须要限制访问频次的接口ide
二、DRF如何限速:函数
经过 rest_framework下面的throttling 模块实现ui
throttling模块主要提供了三种限速方式:spa
1)AnonRateThrottle3d
针对未登陆用户的限速,经过IP地址区分用户rest
2)UserRateThrottle:code
针对已登陆用户,经过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次天天