gpt4 book ai didi

Python 3 - 请求库 - iter_lines - 读取流数据 block 时处理可能的服务器停顿

转载 作者:行者123 更新时间:2023-12-05 01:43:19 25 4
gpt4 key购买 nike

当我从服务器读取数据时,我需要找到一种方法来顺利管理服务器停顿。我写了下面的代码:

def listener():    
resp = requests.get(someurl, stream=True)
if resp.status_code == 200:
for line in resp.iter_lines():
if line:
do_something_with_the_line
print(result)

price_thread = threading.Thread(target=listener, name="StreamingThread", args=[])
trade_thread.start()

代码运行良好,直到服务器出现停顿(API 提供者建议在 10 秒内没有收到“行”时发生停顿)。

如何在我的代码中实现它?换句话说,当出现停顿时,我会尝试在不退出 price_thread 线程的情况下调用 listener 方法。

提前致谢

最佳答案

您可以使用 timeout 属性来确保在指定时间内未收到数据后断开连接,然后重新生成连接:

def listener():
while True:
try:
resp = requests.get(someurl, stream=True, timeout=10)
if resp.status_code == 200:
for line in resp.iter_lines():
if line:
# do_something_with_the_line
pass
elif resp.status_code == 429:
print("Too many reconnects, exiting.")
break
else:
print("Unhandled status `{}` retreived, exiting.".format(resp.status_code))
break
except requests.exceptions.Timeout:
pass # we'll ignore timeout errors and reconnect
except requests.exceptions.RequestException as e:
print("Request exception `{}`, exiting".format(e))
break

您还可以添加一个重新连接计数器,而不是让 while True 无限循环。

关于Python 3 - 请求库 - iter_lines - 读取流数据 block 时处理可能的服务器停顿,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49694126/

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