App lifespan (startup/shutdown)
Run code when the app starts and stops. Used to init the DB and seed data.
Code example
@asynccontextmanager
async def lifespan(app: FastAPI):
init_db() # startup
seed_database()
yield # app runs here
# cleanup on shutdown
app = FastAPI(lifespan=lifespan)
How it works
The lifespan context manager wraps the app's entire run. Code before `yield` runs at startup; code after `yield` runs at shutdown. OpenBenchML uses it to create database tables (init_db) and seed default datasets on boot, and to close all WebSocket connections on shutdown. This replaced the older @app.on_event('startup') decorator and is the recommended pattern for FastAPI 0.93+.
🔍 Where this is used in OpenBenchML
app/main.py — lifespan creates tables, seeds data, cleans up WS on shutdown.