限流Throttling

  • 限流全局配置
  • 复制代码
    REST_FRAMEWORK = {
        # 循环认证,一旦认证成功则不会往下再去认证
        'DEFAULT_AUTHENTICATION_CLASSES': [
            'Restful_api.authentication.CustomerDefinedAuthentication',  # 自定义认证
            'rest_framework.authentication.SessionAuthentication',  # session认证
            'rest_framework.authentication.BasicAuthentication',  # 基础认证
    
        ],
        # 权限的全局配置
        # 'DEFAULT_PERMISSION_CLASSES': [
        #     'rest_framework.permissions.IsAuthenticated',
        # ],
    
        # 限流全局配置
        'DEFAULT_THROTTLE_CLASSES': [
            #     'rest_framework.throttling.UserRateThrottle',  # 已登录用户
            #     'rest_framework.throttling.AnonRateThrottle',  # 未登录用户
            rest_framework.throttling.ScopedRateThrottle  # 单个试图访问次数限流
        ],
        'DEFAULT_THROTTLE_RATES': {
            # 频率
            'user': '5/hour',
            'anon': '3/hour',
            "home2": "2/m",
        }
    }
    复制代码

     

  • 单个试图定制限流时需要加命名空间,使用内部限流时,加一个类即可
  • 复制代码
    class Home2APIView(APIView):
        """限流组件"""
        # 内部限流
        # from rest_framework.throttling import UserRateThrottle,AnonRateThrottle
        # throttle_classes = [AnonRateThrottle]
        # 自定义命名空间(少用:用于定制单个视图)
        throttle_scope = "home2"
    
        def get(self, request):
            return Response(f"登录了视图HOME2{request.user}")
    复制代码

     

  • 自定义限流组件(注释掉全局配置中的限流组件)
  • 自写限流类
  • from rest_framework.throttling import SimpleRateThrottle
    
    
    class OptThrottle(SimpleRateThrottle):
        rate = '5/m'
    
        def get_cache_key(self, request, view):
            return self.get_ident(request)

     

  • 复制代码
    class Home2APIView(APIView):
        """限流组件"""
        # 内部限流
        # from rest_framework.throttling import UserRateThrottle,AnonRateThrottle
        # throttle_classes = [AnonRateThrottle]
        # 自定义命名空间(少用:用于定制单个视图)
        # throttle_scope = "home2"
        # 自定义限流组件
        from opt.Throttling import OptThrottle
        throttle_classes = [OptThrottle]
    
        def get(self, request):
            return Response(f"登录了视图HOME2{request.user}")
    复制代码

     

posted @   Hide_凉辰  阅读(12)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示