[英]What is the use of app.on_event("startup") over just adding lines in the main.py in a fastapi app?
我對使用@app.on_event("startup")
語句的用例感到困惑。 (文檔: https://fastapi.tiangolo.com/advanced/events/?h=on_event )
將代碼放在@app.on_even("startup")
塊中是否比僅在main.py文件的開頭編寫代碼更有優勢?
這兩個替代方案如下所示:
app = FastAPI()
do_something()
@app.get("/")
async def f():
return {"test": 1}
app = FastAPI()
@app.on_event("startup")
async def startup_event():
do_something()
@app.get("/")
async def f():
return {"test": 1}
這個答案並不完整,但我想可以在那里編寫異步代碼,但在頂層並非如此。
因為這段代碼會引發一個錯誤,指出事件循環已經在運行,所以在嘗試運行協程時:
asyncio.get_event_loop().run_until_complete(some_coroutine_function())
但這有效:
@app.on_event("startup")
async def startup_event():
await some_coroutine_function()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.