Django REST框架:每用户限制

mli*_*ner 2 django throttling django-rest-framework

我的用户需要非常高的节流阀,所以他们可以使用很多系统.是否有一种简单的方法可以让它们比其他用户更高的节流?

我环顾四周但没找到任何东西.

mli*_*ner 9

我找到了一种方法来扩展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()
Run Code Online (Sandbox Code Playgroud)

要使用它,只需将您设置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',
},
Run Code Online (Sandbox Code Playgroud)

  • 对我来说,理想的解决方案应该是在 django 管理页面中按组对用户进行分组,并按这些组进行限制。尝试在您的代码和这个想法之间进行混合。如果我发现什么会发布在这里 (2认同)