如何让Python FastAPI异步/等待功能正常工作? [英] How to get Python FastAPI async/await functionality to work properly?
本文介绍了如何让Python FastAPI异步/等待功能正常工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何正确使用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 FastAPI异步/等待功能正常工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文