python - 将进度从 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)
有没有更好的方法来做到这一点?谢谢!
解决方案
推荐阅读
- snapshot - 查询 SnapShot 表并返回单列更改值的日期
- java - 初始化类字段的最佳方法
- c++ - 是否值得将函数调用的结果存储在临时变量中以便在这种情况下进一步重用?
- reactjs - Nest.js Google 登录(passport.js)与 SPA 前端(反应)
- c++ - 针对“种类”层次结构使用可变参数验证 std::function
- javascript - 检查容器中是否有任何矩形(总数:N)相互重叠的最佳方法是什么?
- java - 使用 Reactor Kafka 实现多个接收器以从主题中的多个分区读取
- npm - vega embed中的纱线启动失败
- python - OSError: [Errno 24] 登录 Python 时打开的文件过多
- flutter - 如何将计时器添加到 changenotifier 类