限流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 @ 2023-04-04 19:42  Hide_凉辰  阅读(19)  评论(0)    收藏  举报