【问题标题】:django rest framework throttling per user and per viewdjango rest 框架限制每个用户和每个视图
【发布时间】:2018-10-19 16:02:13
【问题描述】:

我有两个 api 视图(django rest 框架):

class ApiView1(APIView):
    ...
    throttle_classes = (UserRateThrottle, )

和 api 2:

class ApiView2(APIView):
    ...
    throttle_classes = (UserRateThrottle, )

和我的设置:

REST_FRAMEWORK = {
    ...,
    'DEFAULT_THROTTLE_RATES': {
        'user': '5/minute'
    }
}

当请求 ApiView1 五次时,一切正常,但之后当请求 ApiView2 时,我得到一个 http 429 状态代码:

Request was throttled. Expected available in 45 seconds.

问题:我可以对每个用户和每个视图使用限制吗?如果是,怎么做?

【问题讨论】:

    标签: python django-rest-framework throttling


    【解决方案1】:

    是的,你可以。

    对于基于类的视图:

    class YourView(APIView):
        throttle_classes = (UserRateThrottle, )
    
        def get(self, request, format=None):
            content = { ... Your response here ... }
            return Response(content)
    

    对于基于函数的视图,您可以使用装饰器:@throttle_classes([UserRateThrottle])

    _参考:https://www.django-rest-framework.org/api-guide/throttling/

    【讨论】:

    • 谢谢你的回复,我也做了同样的事情,但是当对两个 APIView 使用UserRateThrottle 时,节流总结了两个视图的所有请求计数,换句话说,我想要每个视图的节流
    【解决方案2】:

    因为这是django-rest-framework的功能。

    ScopedRateThrottle 类可用于限制对 API 特定部分的访问。仅当正在访问的视图包含 .throttle_scope 属性时,才会应用此限制。然后将通过将请求的“范围”与唯一的用户 ID 或 IP 地址连接起来,形成唯一的限制键。

    允许的请求速率由 DEFAULT_THROTTLE_RATES 设置使用请求“范围”中的键确定。

    由于您没有将throttle_scope 设置为any 视图,ApiView1 和ApiView2 都使用相同的throttle 范围scope。所以他们共享相同的限制。如果一个视图被过度访问,另一个视图也将是不可接受的。

    在您的场景中,您应该在apiview中设置不同的throttle_scope,并将范围添加到REST_FRAMEWORK.DEFAULT_THROTTLE_RATES。

    如果您有很多限制范围并且不想在settings.py 中添加太多范围,您应该创建自己的Throttle 类并覆盖get_cache_key 函数。

    class MyThrottle(UserRateThrottle):
        def get_cache_key(self, request, view):
            return "throttle_{viewid}_{indent}".format(
                viewid=id(view),
                indent=self.get_indent(request)
            )
    

    这个ThrottleClass可以自动为不同的视图设置不同的范围。

    【讨论】:

    • 如果我想为每个 api 视图设置一个默认的油门速率(单独的速率),那么除了将所有范围(100 个视图然后 100 个范围)添加到设置之外,还有其他解决方案吗?
    • 我更新了答案,你可以使用MyThrottle类。
    猜你喜欢
    • 2021-06-07
    • 2022-11-05
    • 2013-10-08
    • 2016-04-04
    • 2013-10-19
    • 2014-07-06
    • 2021-01-09
    • 2015-05-18
    • 1970-01-01
    相关资源
    最近更新 更多