[英]What is the use of app.on_event("startup") over just adding lines in the main.py in a fastapi app?
I am confused about what the use case for using a @app.on_event("startup")
statement is.我对使用
@app.on_event("startup")
语句的用例感到困惑。 (doc: https://fastapi.tiangolo.com/advanced/events/?h=on_event ) (文档: https://fastapi.tiangolo.com/advanced/events/?h=on_event )
Is there an avantage to putting the code in a @app.on_even("startup")
bloc over just writing it at the beginning of the main.py file?将代码放在
@app.on_even("startup")
块中是否比仅在main.py文件的开头编写代码更有优势?
The two altenatives would look like this:这两个替代方案如下所示:
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}
This answer is not complete but I guess it is possible to write async code there but it isn't so in the top level.这个答案并不完整,但我想可以在那里编写异步代码,但在顶层并非如此。
Because this code will raise an error stating that event loop is already running, when trying to run coroutine:因为这段代码会引发一个错误,指出事件循环已经在运行,所以在尝试运行协程时:
asyncio.get_event_loop().run_until_complete(some_coroutine_function())
But this works:但这有效:
@app.on_event("startup")
async def startup_event():
await some_coroutine_function()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.