[英]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.