繁体   English   中英

Django rest 框架 - 如何限制对 API 端点的请求?

[英]Django rest framework - how can i limit requests to an API endpoint?

我使用 Django Rest 框架创建了 API,现在我正在开发一个速率限制系统,以避免垃圾邮件。 内置的节流系统效果很好,我设法添加了多个节流阀:

REST_FRAMEWORK = {
        # 'DEFAULT_AUTHENTICATION_CLASSES': (
        #     "xapi.authentication_backends.TokenBackend",
        # ),
        'DEFAULT_THROTTLE_CLASSES': [
            'rest_framework.throttling.AnonRateThrottle',
            'rest_framework.throttling.UserRateThrottle'
        ],
        'DEFAULT_THROTTLE_RATES': {
            'anon': '70/minute',
            'user': '70/minute',
            'user_sec': '2/second',
            'user_min': '120/minute',
            'user_hour': '7200/hour',
        },
        
        'DEFAULT_RENDERER_CLASSES': (
        'rest_framework.renderers.JSONRenderer',
        )
    }

在我的views.py中:

class UserSecThrottle(UserRateThrottle):
    scope = 'user_sec'

class UserMinThrottle(UserRateThrottle):
    scope = 'user_min'

class UserHourThrottle(UserRateThrottle):
    scope = 'user_hour'

因此,如果某个用户在一分钟内执行超过 120 个查询,则该用户将被阻止一分钟,如果超出小时限制,则该用户将被阻止一小时。 有什么方法可以决定一个用户被屏蔽了多少? 例如,如果某人在一分钟内执行超过 120 个查询,我想阻止他们 10 分钟。 任何建议表示赞赏。

要创建自定义限制,请覆盖BaseThrottle并实现.allow_request(self, request, view) 如果请求应该被允许,该方法应该返回True ,否则返回False

您也可以选择覆盖.wait()方法。 如果实施, .wait()应返回建议的等待秒数,然后再尝试下一个请求,或者无。 仅当.allow_request()先前返回False时才会调用.wait()方法。

如果实现了.wait()方法并且请求被限制,则 Retry-After header 将包含在响应中。

import random
class CustomThrottle(throttling.BaseThrottle):
# def allow_request(self, request, view):
#     """
#     Return `True` if the request should be allowed, `False` otherwise.
#     """
#     return random.randint(1, 10) != 1

    def wait(self):
        """
        Optionally, return a recommended number of seconds to wait before
        the next request.
        """
        cu_second = 600
        return cu_second

class UserSecThrottle(CustomThrottle,UserRateThrottle):   # or AnonRateThrottle
    scope = 'user_sec'

class ExampleView(APIView):
    throttle_classes = [UserSecThrottle]
    .......

参考: https://www.django-rest-framework.org/api-guide/throttling/#custom-throttles

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM