gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 23:19:10 25 4
gpt4 key购买 nike

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

我想要访问一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com