如何监控Djang中的API节流

2024-06-28 11:45:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在构建一个解决方案,其中我有一个核心API,我已经根据官方文档https://www.django-rest-framework.org/api-guide/throttling/实现了节流。但我想知道我怎样才能monitor the requests so that no genuine user of the app gets blocked and if so should be able to unblock it.

我的设置.py文件

REST_FRAMEWORK = {
    'DEFAULT_THROTTLE_CLASSES': (
        'rest_framework.throttling.ScopedRateThrottle',
    ),
    'DEFAULT_THROTTLE_RATES': {
        'students': '1/minute',
    }
}

还有我的视图.py你知道吗

class StudentViewSet(viewsets.ModelViewSet):
    throttle_scope = 'students'

Tags: the文档pyhttpsrestapidefault核心
1条回答
网友
1楼 · 发布于 2024-06-28 11:45:03

Django REST框架提供的throttle类不允许这样做。您必须创建一个定制的throttle类并覆盖allow_request()来记录节流事件,并提供一些用于白名单的工具。例如,类似这样的事情:

class WhitelistScopedRateThrottle(throttling.ScopedRateThrottle):

    def allow_request(self, request, view):
        allowed = super().allow_request(request, view)
        if not allowed:
            if self.is_whitelisted(request, view)
                return True
            else:
                self.log_throttling(request, view)
                return False
         else:
            return True

    def is_whitelisted(self, request, view):
        ...

    def log_throttling(self, request, view):
        ...

如何最好地实现白名单和日志记录取决于您的具体需求。你知道吗

相关问题 更多 >