【发布时间】:2020-07-06 21:57:42
【问题描述】:
我正在使用 FastApi 并且有一个端点。
我有两个长时间运行的函数,我想使用 asyncio 同时运行它们
因此,我创建了两个函数:
async def get_data_one():
return 'done_one'
async def get_data_two():
return 'done_two'
这些函数从外部网络服务获取数据。
我想同时执行它们,所以我创建了另一个函数来执行它:
async def get_data():
loop = asyncio.get_event_loop()
asyncio.set_event_loop(loop)
task_1 = loop.create_task(get_data_one)
task_2 = loop.create_task(get_data_two)
tasks = (task_1, task_2)
first, second = loop.run_until_complete(asyncio.gather(*tasks))
loop.close()
# I will then perform cpu intensive computation on the results
# for now - assume i am just concatenating the results
return first + second
最后,我有我的端点:
@app.post("/result")
async def get_result_async():
r = await get_data()
return r
即使是这个简单的例子也中断了,当我到达端点时,我得到了以下异常:
RuntimeError:此事件循环已在运行 错误:从未检索到_GatheringFuture 异常 未来:<_gatheringfuture> AttributeError: 'function' 对象没有属性 'send'
这是一个简化的代码,但我真的很感激如何以正确的方式来做。
【问题讨论】:
标签: python python-3.x python-asyncio fastapi