Django之DRF-- API限速

什么场景下需要限制访问频次呢?

  1)防爬虫:爬虫可能会在短时间内大量的访问服务接口,增加服务器压力

  2)对于需要限制访问频次的接口

具体使用配置如下:

1,settings.py加入配置

REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    # 限速
    'DEFAULT_THROTTLE_CLASSES': (
        'rest_framework.throttling.AnonRateThrottle',  # 匿名限速  针对未登录用户的限速,通过IP地址区分用户
        'rest_framework.throttling.UserRateThrottle'  # 登录限速   针对已登录用户,通过user id来区分用户
    ),
    'DEFAULT_THROTTLE_RATES': {
        #访问频次单位有:second,minute,hour和day
        'anon': '2/minute',  
        'user': '3/minute'
    }
}

2,视图文件加入配置

from rest_framework.throttling import UserRateThrottle, AnonRateThrottle # 限速
class SupplierInfo(APIView):
    def post(self,request):
        throttle_classes = (UserRateThrottle, AnonRateThrottle)  # 限速配置
        # values 取某字段  返回字典类型
        sup = Supplier.objects.all()
        ser = serializers.SupplierinfoSerializers(many=True,instance=sup)
        return Response(data=ser.data,status=200)
原文地址:https://www.cnblogs.com/xcsg/p/11617702.html