Customizing events
The FastAPI framework has special functions called event handlers that execute before the application starts up and during shutdown. These events are activated every time the uvicorn
or hypercorn
server reloads. Event handlers can also be coroutines.
Defining the startup event
The startup event is an event handler that the server executes when it starts up. We decorate the function with the @app.on_event("startup")
decorator to create a startup event. Applications may require a startup event to centralize some transactions, such as the initial configuration of some components or the set up of data-related resources. The following example is the application startup event that opens a database connection for the GINO repository transactions:
app = FastAPI() @app.on_event("startup") async def initialize(): engine = await db.set_bind("postgresql+asyncpg:// ...