gpt4 book ai didi

python - 如何让 Python FastAPI 异步/等待功能正常工作?

转载 作者:行者123 更新时间:2023-12-04 11:08:15 31 4
gpt4 key购买 nike

如何正确利用 FastAPI 路由中的异步功能?

以下代码片段需要 10 秒才能完成对我的 /home 的调用。路线,而我预计它只需要 5 秒。

from fastapi import FastAPI
import time

app = FastAPI()

async def my_func_1():
"""
my func 1
"""
print('Func1 started..!!')
time.sleep(5)
print('Func1 ended..!!')

return 'a..!!'

async def my_func_2():
"""
my func 2
"""
print('Func2 started..!!')
time.sleep(5)
print('Func2 ended..!!')

return 'b..!!'

@app.get("/home")
async def root():
"""
my home route
"""
start = time.time()
a = await my_func_1()
b = await my_func_2()
end = time.time()
print('It took {} seconds to finish execution.'.format(round(end-start)))

return {
'a': a,
'b': b
}

我得到以下结果,看起来是非异步的:
λ uvicorn fapi_test:app --reload
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [5116]
INFO: Started server process [7780]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: 127.0.0.1:51862 - "GET / HTTP/1.1" 404
Func1 started..!!
Func1 ended..!!
Func2 started..!!
Func2 ended..!!
It took 10 seconds to finish execution.
INFO: 127.0.0.1:51868 - "GET /home HTTP/1.1" 200

但是,我希望 FastAPI 打印如下:
Func1 started..!!
Func2 started..!!
Func1 ended..!!
Func2 ended..!!
It took 5 seconds to finish execution.

如果我做错了什么,请纠正我?

最佳答案

time.sleep正在阻塞,你应该使用 asyncio.sleep ,还有.gather.wait聚合作业。这在 Python 中有详细记录和 FastAPI .

关于python - 如何让 Python FastAPI 异步/等待功能正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61316540/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com