简体   繁体   中英

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. (doc: 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?

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM