Django Rest framework 频率控制配置说明
全局设置
setting.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| 'DEFAULT_THROTTLE_CLASSES': ( 'rest_framework.throttling.AnonRateThrottle', 'rest_framework.throttling.UserRateThrottle', 'rest_framework.throttling.ScopedRateThrottle', 'app.throttling.UserRecordThrottle', ), 'DEFAULT_THROTTLE_RATES': { 'anon': '1000/day', 'user': '20000/day', 'ttxs': '10/minute', 'user_record': None },
|
自定义
throttling.py
1 2 3 4 5
| from rest_framework.throttling import UserRateThrottle, AnonRateThrottle class UserRecordThrottle(UserRateThrottle): scope = 'user_record' rate = '5/minute'
|
使用方式说明:
方式一: 在views.py中使用,设置为throttle_classes = ([UserRecordThrottle,])
方式二: 在setting.py中设置,
- 在DEFAULT_THROTTLE_CLASSES添加’app.throttling.UserRecordThrottle’
- DEFAULT_THROTTLE_RATES中添加user_record
- 在views.py中通过throttle_scope = ‘user_record’ 调用
类视图使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| from rest_framework.response import Response from rest_framework.throttling import UserRateThrottle from rest_framework.views import APIView class ExampleView(APIView): throttle_classes = ([UserRateThrottle,UserParserRecordThrottle]) throttle_scope = 'ttxs' def get(self, request, format=None): pass return Response('ok') { "msg": "request was throttled.", "code": 10429 }
|
其他说明
- 匿名用户频率如果设置大于授权用户频率,则以授权用户频率为准
- 频率限制是针对单个接口的频率,而不是所有接口的频率