我正在为我使用django rest framework开发的api创建一个自定义throatting,目前有两个订阅计划,每个计划都有自己的配额,因此在throatting.py
中,我创建了一个自定义类,用于获取用户配额并将其覆盖为默认设置:
from rest_framework.throttling import UserRateThrottle
def get_user_daily_limit(user):
# Some calculations
# return the daily quota for user, f.ex: 20 request
class SubscriptionDailyRateThrottle(UserRateThrottle):
scope = "subscription"
def __init__(self):
super().__init__()
def allow_request(self, request, view):
if request.user.is_staff:
return True
if request.user.is_authenticated:
user_daily_limit = get_user_daily_limit(request.user)
if user_daily_limit:
self.duration = 86400
self.num_requests = user_daily_limit
else:
return True
if self.rate is None:
return True
self.key = self.get_cache_key(request, view)
if self.key is None:
return True
self.history = self.cache.get(self.key, [])
self.now = self.timer()
while self.history and self.history[-1] <= self.now - self.duration:
self.history.pop()
if len(self.history) >= self.num_requests:
return self.throttle_failure()
return self.throttle_success()
这是我的settings.py
:
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.TokenAuthentication',
],
'DEFAULT_THROTTLE_CLASSES': [
'rest_framework.throttling.UserRateThrottle',
'app.throttling.SubscriptionDailyRateThrottle'
],
'DEFAULT_THROTTLE_RATES': {
'user': '5/second',
'subscription': '16/day'
}
}
我检查了the tutorial我一直在跟踪,一切似乎都很好,但当我测试它执行请求时,我既看不到请求之间的5秒,也看不到每天最多16个请求,我遗漏了什么
目前没有回答
相关问题 更多 >
编程相关推荐