DRF限制访问频次

官方文档: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次每天

 

        

 

 

  

转载于:https://www.cnblogs.com/fiona-zhong/p/10511603.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值