English 中文(简体)
FastAPI - FastAPI Event Handlers
  • 时间:2024-12-22

FastAPI - FastAPI Event Handlers


Previous Page Next Page  

Event handlers are the functions to be executed when a certain identified event occurs. In FastAPI, two such events are identified − startup and shutdown. FastAPI’s apppcation object has on_event() decorator that uses one of these events as an argument. The function registered with this decorator is fired when the corresponding event occurs.

The startup event occurs before the development server starts and the registered function is typically used to perform certain initiapzation tasks, estabpshing connection with the database etc. The event handler of shutdown event is called just before the apppcation shutdown.

Example

Here is a simple example of startup and shutdown event handlers. As the app starts, the starting time is echoed in the console log. Similarly, when the server is stopped by pressing ctrl+c, the shutdown time is also displayed.

main.py


from fastapi import FastAPI
import datetime
app = FastAPI()
@app.on_event("startup")
async def startup_event():
   print( Server started : , datetime.datetime.now())
@app.on_event("shutdown")
async def shutdown_event():
   print( server Shutdown : , datetime.datetime.now())

Output

It will produce the following output −


uvicorn main:app --reload
INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit)
INFO: Started reloader process [28720]
INFO: Started server process [28722]
INFO: Waiting for apppcation startup.
Server started: 2021-11-23 23:51:45.907691
INFO: Apppcation startup complete.
INFO: Shutting down
INFO: Waiting for apppcation
server Shutdown: 2021-11-23 23:51:50.82955
INFO: Apppcation shutdown com
INFO: Finished server process
Advertisements