首页 > 解决方案 > DRF 错误的节流触发器

问题描述

我有一个APIView为员工用户设置节流的地方。我也在范围中添加了视图名称。这是代码片段:

权限.py

class IsStaffUser(BasePermission):

    def has_permission(self, request, view):
        return request.user and request.user.is_authenticated and request.user.is_staff

视图.py

from rest_framework.views import APIView
from myprj.somewhere.permissions import IsStaffUser
from myprj.somewhere.throttling import MyThrottleRate


class BaseView(APIView):
    permission_classes = (IsStaffUser,)

class MyView(BaseView):
    throttle_classes = (MyThrottleRate,)

    def get(self, request, pk):
        # some stuff

节流.py

from rest_framework.throttling import UserRateThrottle

class BaseThrottling(UserRateThrottle):
    cache_format = 'throttle_%(scope)s_%(ident)s_(view_name)s'

    def get_rate(self):
        """
        Determine the string representation of the allowed request rate.
        """
        try:
            return self.THROTTLE_RATES[self.scope]
        except KeyError:
            msg = "No default throttle rate set for '%s' scope" % self.scope
            raise ImproperlyConfigured(msg)

    def get_cache_key(self, request, view):
        if request.user.is_authenticated:
            ident = request.user.pk
            view_name = view.request.resolver_match.func.__name__

            cache_format = self.cache_format % {
                'scope': self.scope,
                'ident': ident,
                'view_name': view_name
            }
            return cache_format
        else:
            raise APIException('You are not authorised')

class MyThrottleRate(BaseThrottling):
    THROTTLE_RATES = {
        'user': '20/hour',
    }

我已将费率设置为 20/小时,但我429会在当天的第一个请求时获得状态代码。我寻找解决方案,但找不到解决方案。请帮我定位错误。

注意:我们使用apachewithmod_wsgi

标签: pythondjangodjango-rest-framework

解决方案


推荐阅读