Python - 在 asyncio 中运行函数的正确方法是什么?

Inf*_*ner 1 python python-3.x python-asyncio fastapi

我正在使用 FastApi 并且有一个端点。

我有两个长时间运行的函数,我想使用 asyncio 同时运行

因此,我创建了两个函数:

async def get_data_one():
    return 'done_one'

async def get_data_two():
    return 'done_two'
Run Code Online (Sandbox Code Playgroud)

这些函数从外部 Web 服务获取数据。

我想同时执行它们,所以我创建了另一个函数来执行它:

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
Run Code Online (Sandbox Code Playgroud)

最后,我有我的终点:

@app.post("/result")
async def get_result_async():
    r = await get_data()

    return r
Run Code Online (Sandbox Code Playgroud)

即使这个简单的示例也会崩溃,当我到达端点时,我会收到以下异常:

RuntimeError:此事件循环已在运行错误:_GatheringFuture 异常从未检索到未来:<_GatheringFuture 完成异常 = AttributeError(“‘function’对象没有属性‘send’”,)> AttributeError:‘function’对象没有属性‘send’ '

这是一个简化的代码,但我真的很感激如何以正确的方式做到这一点。

AKX*_*AKX 7

在 FastAPI 上下文中,您永远不需要运行 asyncio 循环;只要您的服务器进程存在,它就始终运行。

因此,您所需要的只是

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())
Run Code Online (Sandbox Code Playgroud)