[英]Python - What is the right way to run functions in asyncio?
I am using FastApi and have one endpoint.我正在使用 FastApi 并且有一个端点。
I have two long running functions which I want to run concurrently using asyncio我有两个长时间运行的函数,我想使用 asyncio 同时运行它们
Therefore, I have created two functions:因此,我创建了两个函数:
async def get_data_one():
return 'done_one'
async def get_data_two():
return 'done_two'
These functions get data from external webservices.这些函数从外部 Web 服务获取数据。
I want to execute them concurrently so I have created a another function that does it:我想同时执行它们,所以我创建了另一个 function 来执行它:
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
Finally, I have my endpoint:最后,我有我的端点:
@app.post("/result")
async def get_result_async():
r = await get_data()
return r
Even this simple example breaks and I get the following exception when I hit the endpoint:即使是这个简单的示例也会中断,当我到达端点时会出现以下异常:
RuntimeError: This event loop is already running ERROR: _GatheringFuture exception was never retrieved future: <_GatheringFuture finished exception=AttributeError("'function' object has no attribute 'send'",)> AttributeError: 'function' object has no attribute 'send' RuntimeError:此事件循环已在运行错误:_GatheringFuture 异常未检索到未来:<_GatheringFuture 完成异常=AttributeError(“'function' object 没有属性'send'”,)> AttributeError:'function' object 'send 没有属性'
This is a simplified code but I would really appreciate how to do it the right way.这是一个简化的代码,但我真的很感激如何以正确的方式去做。
When in FastAPI context, you never need to run an asyncio loop;在 FastAPI 上下文中,您永远不需要运行 asyncio 循环; it's always running for as long as your server process lives.
只要您的服务器进程存在,它就会一直运行。
Therefore, all you need is因此,您只需要
import asyncio
async def get_data_one():
return "done_one"
async def get_data_two():
return "done_two"
async def get_data():
a, b = await asyncio.gather(get_data_one(), get_data_two())
return a + b
#@route decorator here...
async def get_result_async():
r = await get_data()
print("Get_data said:", r)
return r
# (this is approximately what is done under the hood,
# presented here to make this a self-contained example)
asyncio.run(get_result_async())
It's as simple as:它很简单:
async def get_data():
first, second = await asyncio.gather(
get_data_one(),
get_data_two(),
)
return first + second
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.