- 限流全局配置
-
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}")