Django REST 如何设置节流周期以允许 10 分钟内允许一个请求?

问题描述 投票:0回答:3

文档说该句点应该是以下之一:

('s', 'sec', 'm', 'min', 'h', 'hour', 'd', 'day')
。我很好奇是否可以将周期设置为类似
1/10min

python django django-rest-framework throttling
3个回答
11
投票

查看代码文档,您无法“开箱即用”执行此操作。但我确实看到了描述的可能性,可以根据现有的油门之一制作自己的自定义油门

from rest_framework.throttling import AnonRateThrottle


class AnonTenPerTenMinutesThrottle(AnonRateThrottle):
    def parse_rate(self, rate):
        """
        Given the request rate string, return a two tuple of:
        <allowed number of requests>, <period of time in seconds>

        So we always return a rate for 10 request per 10 minutes.

        Args:
            string: rate to be parsed, which we ignore.

        Returns:
            tuple:  <allowed number of requests>, <period of time in seconds>
        """
        return (10, 600)

5
投票

基本上 XY 说的是真的,但它可能不起作用,因为你仍然必须像这样输入费率:

from rest_framework.throttling import AnonRateThrottle

class AnonTenPerTenMinutesThrottle(AnonRateThrottle):
    

    rate = '1/s' # <<<<< This line is very important
    # You just can enter any rate you want it will directly be overwritten by parse_rate
    

    def parse_rate(self, rate):
        """
        Given the request rate string, return a two tuple of:
        <allowed number of requests>, <period of time in seconds>

        So we always return a rate for 10 request per 10 minutes.

        Args:
            string: rate to be parsed, which we ignore.

        Returns:
            tuple:  <allowed number of requests>, <period of time in seconds>
        """
        return (10, 600) # 10 Requests per 600 seconds (10 minutes)

0
投票

您可以定义下面指定的自定义方法

parse_custom_rate()
,然后使用方便的格式
rate = "1/10m"
。对我有用
djangorestframework==3.14.0
。确保在速率变量中使用单个字母时间间隔
s, m, h, d

from rest_framework.throttling import AnonRateThrottle

def parse_custom_rate(custom_rate: str) -> tuple[int, int]:
    if custom_rate is None:
        raise ValueError
    num, period = custom_rate.split('/')
    num_requests = int(num)
    duration = {'s': 1, 'm': 60, 'h': 3600, 'd': 86400}[period[-1]]
    seconds = int(period[:-1]) * duration
    return (num_requests, seconds)


class AnonOnceInTenMinutesThrottle(AnonRateThrottle):
    rate = "1/10m" # s, m, h, d

    def parse_rate(self, rate):
        return parse_custom_rate(self.rate)
© www.soinside.com 2019 - 2024. All rights reserved.