在特定时间段后停止从API提取数据

问题描述 投票:0回答:1

我正在使用python v3从流API提取一些数据,我需要在60秒后停止提取数据。另外,如果有人对chunk_size或流媒体的替代方法有任何建议,我也会开放的。到目前为止,这就是我所拥有的:

response = requests.get('link to site', stream=True)

for data in response.iter_content(chunk_size=100):
    print(data)
python api python-requests streaming
1个回答
0
投票

猜测多于答案,但您可以设置一个计时器,然后关闭响应。也许可以做到,但是我没有很好的方法来测试它。我不知道关闭响应时会期待哪个异常,因此我将它们全部捕获并打印出来,以便可以更改代码。

import threading

response = requests.get('link to site', stream=True)
timer = threading.Timer(60, response.close)
try:
    timer.start()
    for data in response.iter_content(chunk_size=100):
        print(data)
    except Exception as e:
        print("you want to catch this", e)
finally:
    timer.cancel()
© www.soinside.com 2019 - 2024. All rights reserved.