如何限制Python 3中多线程程序中的API调用?

Jos*_*h.F 5 python api multithreading

经过大量研究,我不确定最佳实践是什么,我的以下想法是否合适?

我想要访问一个 API,该 API 将我可以进行的调用总数限制为每分钟 50 次。

我的程序有多个独立运行的线程。

如何限制我的程序保持在阈值以下?

我的想法是创建一个队列,并每 X 秒向其中添加一件事,其中 X = thread_count/allowed_calls*60。然后需要一个单独的线程来处理这些请求。(还有一个单独的线程用于定期添加)

对于这样的事情,最佳实践是什么?有没有一种方法可以实现这一目标,而不需要为每个小功能提供完全独立的线程?

Adr*_*ida 5

为什么不创建一个使用内部变量来控制调用次数和第二次调用的类?

从https://github.com/lucjon/Py-StackExchange/blob/master/stackexchange/web.py中删除了此代码

基本上,它会检查您的呼叫数量是否超过您需要的数量,如果是这种情况则停止。如果您使用多线程(如 Pool),请将函数请求作为要执行的函数传递。

class WebRequestManager(object):
    # When we last made a request
    window = datetime.datetime.now()
    # Number of requests since last throttle window
    num_requests = 0

    def request(self, url, params):
        now = datetime.datetime.now()

        # Before we do the actual request, are we going to be throttled?
        def halt(wait_time):
            if self.throttle_stop:
                raise TooManyRequestsError()
            else:
                # Wait the required time, plus a bit of extra padding time.
                time.sleep(wait_time + 0.1)

        if (now - WebRequestManager.window).seconds >= 1:
            WebRequestManager.window = now
            WebRequestManager.num_requests = 0

        WebRequestManager.num_requests += 1
        if WebRequestManager.num_requests > 30:
            halt(5 - (WebRequestManager.window - now).seconds)

        request = urllib.request.Request(url)
        ...
Run Code Online (Sandbox Code Playgroud)

  • 没有意识到我从未接受过这一点。谢谢你,近十年后:D (2认同)