如何设置自定义速率,以在 django rest 框架中进行节流?

How to set custom rates, for throttling in django rest framework?

我正在使用 DRF 进行节流,根据 document 我可以为我的费率选择以下选项之一: 秒、分钟、小时或天。

但问题是,我想要一个自定义速率,例如,每 10 分钟 3 个请求。

在 DRF 中可以吗?

您应该可以通过扩展 SimpleRateThrottle or any other class that extends SimpleRateThrottle (UserRateThrottle etc.).

来实现这一点

看看parse_rate method of SimpleRateThrottle:

It takes request rate string as input and returns a two tuple of: (allowed number of requests, period of time in seconds)

因此,如果您编写 class 来覆盖此解析逻辑,您就可以开始了。

例如:

from pytimeparse.timeparse import timeparse

class ExtendedRateThrottle(throttling.UserRateThrottle):
    def parse_rate(self, rate):
        """
        Given the request rate string, return a two tuple of:
        <allowed number of requests>, <period of time in seconds>
        """
      if rate is None:
          return (None, None)
      num, period = rate.split('/')
      num_requests = int(num)
      duration = timeparse(period)
      return (num_requests, duration)

Run this example 并查看 3/10m 解析为 (3, 600)

现在使用此 class 作为您的 DEFAULT_THROTTLE_CLASSES 或者您可以使用任何其他限制 class.