限流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}")
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!