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

标签 python multithreading api

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

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

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

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

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

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

最佳答案

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

这段代码是从 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)
        ...

关于python - 如何限制Python 3中多线程程序中的API调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26200661/

相关文章:

multithreading - Node.js,进程和线程问题

c# - 跨线程操作在 MDIParent 中无效

javascript - 类型错误 : cannot read property of undefined (reading 'map' ) while fetching from API

python - 在 GTK+ TreeView 中显示异构数据

python - 以 10 为基数的 int() 的文字无效 : '2,674'

python - 数据透视表到字典

python - 将 pandas 偏移量转换为 python 日期

java - 当不再有线程持有某个对象时,如何从 ConcurrentHashMap 中删除项目?

c# - 是否有用于 Azure 资源管理 API 调用的 C# sdk/包装器?

javascript - 如何在函数外重用 Javascript 变量