简体   繁体   English

将请求速率限制为CGI脚本中的API

[英]Limit the rate of requests to an API in a CGI script

The script that I'm writing sometimes makes requests to an API and the API requires that requests are limited to a maximum of 1 per second. 我正在编写的脚本有时会向API发出请求,而该API则要求每秒请求的最大数量限制为1。

What is the most straight forward way of limiting my requests to the API to 1 every second? 将我对API的请求每秒限制为1的最直接的方法是什么?

Would it involve storing the current time in a file each time a request is made? 是否会在每次发出请求时将当前时间存储在文件中?

You could use a separate thread for the CGI calls and a queuing mechanism that loops with a call to sleep on each iteration. 您可以为CGI调用使用一个单独的线程,并使用一个排队机制来循环每次调用时进入睡眠状态。

From 15.3. 15.3。 time 时间

time.sleep(secs) Suspend execution for the given number of seconds. time.sleep(secs)暂停执行指定的秒数。 The argument may be a floating point number to indicate a more precise sleep time. 该参数可以是浮点数,以指示更精确的睡眠时间。 The actual suspension time may be less than that requested because any caught signal will terminate the sleep() following execution of that signal's catching routine. 实际的暂停时间可能少于请求的暂停时间,因为任何捕获到的信号都会在执行该信号的捕获例程后终止sleep()。 Also, the suspension time may be longer than requested by an arbitrary amount because of the scheduling of other activity in the system. 而且,由于系统中其他活动的调度,暂停时间可能比请求的时间长任意数量。

One can use a rate-limiting python decorator on the function one wishes to rate-limit, like this one from Greg Burek: 可以在希望进行速率限制的函数上使用速率限制python装饰器 ,例如Greg Burek的代码:

import time

def RateLimited(maxPerSecond):
    minInterval = 1.0 / float(maxPerSecond)
    def decorate(func):
        lastTimeCalled = [0.0]
        def rateLimitedFunction(*args,**kargs):
            elapsed = time.clock() - lastTimeCalled[0]
            leftToWait = minInterval - elapsed
            if leftToWait>0:
                time.sleep(leftToWait)
            ret = func(*args,**kargs)
            lastTimeCalled[0] = time.clock()
            return ret
        return rateLimitedFunction
    return decorate

@RateLimited(2)  # 2 per second at most
def PrintNumber(num):
    print num

if __name__ == "__main__":
    print "This should print 1,2,3... at about 2 per second."
    for i in range(1,100):
        PrintNumber(i)

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

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