Middle
What is lifespan in FastAPI? What mechanisms are available for executing code before startup and after shutdown?
sobes.tech AI
Answer from AI
In FastAPI, lifespan is a mechanism for managing the application's lifecycle, allowing code to be executed at server startup and shutdown.
Special functions are used to run code before the application starts and after it stops, which can be defined using a context manager or the @app.on_event decorator:
@app.on_event("startup")— code that runs when the application starts.@app.on_event("shutdown")— code that runs when the application stops.
Example using events:
from fastapi import FastAPI
app = FastAPI()
@app.on_event("startup")
async def startup_event():
print("Application is starting: initializing resources")
@app.on_event("shutdown")
async def shutdown_event():
print("Application is stopping: releasing resources")
Also, in FastAPI 0.70+, a lifespan parameter was introduced, which allows setting an asynchronous context manager for more flexible lifecycle management:
from contextlib import asynccontextmanager
from fastapi import FastAPI
@asynccontextmanager
def lifespan(app: FastAPI):
# Code at startup
print("Starting")
yield
# Code at shutdown
print("Stopping")
app = FastAPI(lifespan=lifespan)
Thus, lifespan is a modern way to centrally manage starting and stopping the application, while @app.on_event is a more traditional method for the same purposes.