当 stream = True 但数据并不总是流入时,如何退出 Python 请求获取?

How can I exit a Python requests get when stream = True but data is not always flowing in?

我正在使用请求在网页上发出获取请求,在该网页上,当现实世界中发生事件时会添加新数据。只要 window 打开,我就想继续获取这些数据,所以我设置了 stream = True,然后在数据流入时逐行迭代。

page = requests.get(url, headers=headers, stream=True)
# Process the LiveLog data until stopped from exterior source
for html_line in page.iter_lines(chunk_size=1):
    # Do other work here

我对这部分没有问题,但是当谈到退出这个循环时,我 运行 遇到了问题。通过查看其他 Whosebug 线程,我了解到我无法捕获任何信号,因为我的 for 循环正在阻塞。相反,我尝试使用以下代码,它确实有效,但有一个大问题。

if QThread.currentThread().isInterruptionRequested():
    break

此代码将使我脱离循环,但我发现 for 循环迭代的唯一时间是将新数据引入 get 时,在我的情况下,这是不连续的。我可以在几分钟或更长时间内没有任何新数据,并且不想在我再次通过循环检查是否请求中断之前必须等待这些新数据登陆。

如何在用户操作后立即退出循环?

您可以试试 aiohttp 库 https://github.com/aio-libs/aiohttp, and specifically https://aiohttp.readthedocs.io/en/stable/streams.html#asynchronous-iteration-support。它看起来像:

import asyncio
import aiohttp

async def main():
    url = 'https://httpbin.org/stream/20'
    chunk_size = 1024
    async with aiohttp.ClientSession() as session:
        async with session.get(url) as resp:
            while True:
                data = await resp.content.readline():
                print(data) # do work here

if __name__ == "__main__":
    asyncio.run(main())

值得注意的是 resp.content 是一个 StreamReader 所以你可以使用其他可用的方法 https://aiohttp.readthedocs.io/en/stable/streams.html#aiohttp.StreamReader