gpt4 book ai didi

Django REST框架: Per-user throttles

转载 作者:行者123 更新时间:2023-12-01 07:25:04 24 4
gpt4 key购买 nike

我的用户需要非常高的 throttle ,因此他们可以大量使用该系统。有没有一种简单的方法可以使它们比其他用户拥有更高的 throttle ?

我环顾四周,但未发现任何东西。

最佳答案

我想出了一种方法,可以通过扩展UserRateThrottle并将特殊用户添加到我的设置文件中。

此类仅覆盖allow_request方法,并添加了一些特殊的逻辑以查看是否在OVERRIDE_THROTTLE_RATES变量中列出了用户名:

class ExceptionalUserRateThrottle(UserRateThrottle):
def allow_request(self, request, view):
"""
Give special access to a few special accounts.

Mirrors code in super class with minor tweaks.
"""
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()

# Adjust if user has special privileges.
override_rate = settings.REST_FRAMEWORK['OVERRIDE_THROTTLE_RATES'].get(
request.user.username,
None,
)
if override_rate is not None:
self.num_requests, self.duration = self.parse_rate(override_rate)

# Drop any requests from the history which have now passed the
# throttle duration
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()

要使用此功能,只需将 DEFAULT_THROTTLE_CLASS设置为此类,然后将一些特殊用户放入 OVERRIDE_THROTTLE_RATES中,如下所示:
'DEFAULT_THROTTLE_CLASSES': (
'rest_framework.throttling.AnonRateThrottle',
'cl.api.utils.ExceptionalUserRateThrottle',
),
'DEFAULT_THROTTLE_RATES': {
'anon': '100/day',
'user': '1000/hour',
},
'OVERRIDE_THROTTLE_RATES': {
'scout': '10000/hour',
'scout_test': '10000/hour',
},

关于Django REST框架: Per-user throttles,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34538695/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com