簡體   English   中英

當stream = True但數據並不總是流入時,如何退出Python請求?

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

我正在使用請求在網頁上發出獲取,其中在現實世界中發生事件時添加新數據。 只要窗口打開,我就想繼續獲取這些數據,所以我設置了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

這部分我沒有問題,但是在退出這個循環時我遇到了問題。 通過查看其他 StackOverflow 線程,我明白我無法捕獲任何信號,因為我的 for 循環阻塞了。 相反,我嘗試使用以下代碼,它確實有效,但有一個大問題。

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

這段代碼將使我擺脫循環,但我發現 for 循環迭代的唯一時間是將新數據引入 get 時,在我的情況下,這不是連續的。 我可以在幾分鍾或更長時間內沒有任何新數據,並且不想在我再次通過我的循環檢查是否請求中斷之前等待這些新數據登陸。

如何在用戶操作后立即退出循環?

您可以嘗試 aiohttp 庫https://github.com/aio-libs/aiohttp ,特別是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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM