Python 发出 10 个请求时休眠

Python sleep when making 10 requests

我正在使用

requests.get() 

一次又一次地调用同一个服务器,但我限制在每分钟 30 个请求。当我发出 30 个请求时,如何让程序休眠一分钟。挑战是

requests.get()

在我的代码中到处都是,我不能把它们放在一个循环中。

您可以使用 Adapter Pattern 来包装请求。像这样:

class RequestLimiter:
    def __init__(self):
        self.count = 0
    def get(self, *args, **kwargs):
        if self.count == 30:
            time.sleep(60)
            self.count = 0
            return requests.get(*args, **kwargs)
        else:
            self.count += 1
            requests.get(*args, **kwargs)

def main():
    # If this is through your whole program, 
    # you might want to make this global- be careful with that!
    r = RequestLimiter()
    r.get(url, args)

根据您的要求,您可能想要更改其中的一些内容。例如,根据编码,无论 get 成功还是失败,您的计数都会增加。这可能是也可能不是你想要的。如果您确实决定创建此 class 的全局实例,那么您必须担心对 count 变量的并发访问(如果您使用并发)。