DRF------限流组件

限制用户访问频率。 

场景:短信验证码,一天只可以发送50次

一、先安装 redis

 pip install django-redis

二、settings.py中配置缓存到redis

CACHES={
    'default':{
        'BACKEND':'django_redis.cache.RedisCache',
        'LOCATION':'redis://127.0.0.1:6379',
        'OPTIONS':{
            'CLIENT_CLASS':'django_redis.client.DefaultClient',
            'PASSWORD':'qwe123',
        }
    }
}

三、编写限流类

from rest_framework.throttling import SimpleRateThrottle     # 限流组件
from django.core.cache import cache as default_cache
from rest_framework import exceptions


# 自定义异常
class ThrottledException(exceptions.APIException):
    pass


# 自定义限流类
class MyRateThrottle(SimpleRateThrottle):

    cache = default_cache      # 读取django中的缓存配置,这样用户的访问记录被放在缓存中 (前提:settings已经配置了缓存)
    scope='user'  # 构造缓存中的key
    cache_format = 'throttle_%(scope)s_%(ident)s'

    #设置访问频率,例如:1分钟允许访问10次
    #其他:'s','sec','m','min','h','hour','d','day'
    THROTTLE_RATES = {'user':"10/m"}   # 'user'和scope的user保持一致。  设置访问频率 :1分钟只能访问10次

    # 生成用户的唯一标识
    def get_cache_key(self, request, view):
        if request.user:
            ident=request.user.pk  # 用户id
        else:
            ident=self.get_ident(request)   # 获取请求用户的ip (取request中找请求头)
        return self.cache_format % {'scope':self.scope,'ident':ident}

    # 用户超过访问限制后的处理
    def throttle_failure(self):
        wait=self.wait()
        detail={
            'code':1005,
            'data':'访问频率限制',
            'detail':'需要等待{}s才能访问'.format(int(wait))
        }
        raise ThrottledException(detail)

四 api中引用

from userAuth.xianliu import MyRateThrottle
'''
我的订单
'''
class OrderView(APIView):
    # 引入自己编写的认证类,如果认证通过,才会执行后面的方法
    authentication_classes = [TokenAuthentication,]
    # 引入权限组件
    permission_classes = [PermissionA,]
    # 引入限流组件
    throttle_classes = [MyRateThrottle,]

    def get(self,request,*args,**kwargs):
        print(f'--------: {request.user}')
        print(f'--------: {request.auth}')
        return Response({'code':1002,'data':'我的订单成功'})

五 多个限流类

六 全局配置

# 后续DRF相关配置在这里填充
REST_FRAMEWORK={
    # 'DEFAULT_THROTTLE_CLASSES':['限流类',]
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值