首页 > 解决方案 > 将进度从 Asyncio 循环发送到网站

问题描述

我有一个带有 Flask API 的 Python 应用程序,它使用 asyncio 执行一些并行工作。这需要一段时间才能完成,所以每隔一段时间我想使用服务器发送的事件向网站报告进度。

我想出的最好的主意(我知道这是垃圾并且完全不是线程安全的,但这只是一个例子):

import asyncio
from threading import Thread

counter = 0

def background_loop(loop):
    asyncio.set_event_loop(loop)
    loop.run_forever()

async def something(t):
    await asyncio.sleep(t)

async def generator():
    pending = [something(t) for t in range(0, 5)]
    while pending:
        done, pending = await asyncio.wait(pending, return_when=asyncio.FIRST_COMPLETED)
        for task in done:
            yield task.result()

async def consumer():
    global counter
    async for _ in generator():
        counter += 1

loop = asyncio.new_event_loop()
t = Thread(target=background_loop, args=(loop,), daemon=True)
t.start()

#here would be the endpoint
task = asyncio.run_coroutine_threadsafe(consumer(), loop)
while counter != 5:
    print(counter)

有没有更好的方法来做到这一点?谢谢!

标签: pythonflaskserver-sent-eventspython-asyncio

解决方案


推荐阅读