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

Jay*_*K23 6 python django

我使用 Django Rest Framework 创建了一个 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',
        )
    }
Run Code Online (Sandbox Code Playgroud)

而在我的views.py

class UserSecThrottle(UserRateThrottle):
    scope = 'user_sec'

class UserMinThrottle(UserRateThrottle):
    scope = 'user_min'

class UserHourThrottle(UserRateThrottle):
    scope = 'user_hour'
Run Code Online (Sandbox Code Playgroud)

因此,如果某个用户在一分钟内执行超过 120 个查询,该用户将被阻止一分钟,如果违反小时限制,该用户将被阻止一小时。有什么方法可以决定用户被阻止的程度吗?例如,如果某人在一分钟内执行超过 120 次查询,我想阻止某人 10 分钟。任何建议表示赞赏。

Pra*_*dip 5

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

(可选)您也可以覆盖该.wait()方法。如果实现,.wait()应该返回一个推荐的在尝试下一个请求之前等待的秒数,或者 None。.wait()仅当.allow_request()先前返回 时才会调用该方法False

如果.wait()实现了该方法并且请求受到限制,则响应中将包含 Retry-After 标头。

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]
    .......
Run Code Online (Sandbox Code Playgroud)

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