MAIN FEEDS
Do you want to continue?
https://www.reddit.com/r/FastAPI/comments/1mq7ed8/lifespan_on_fastapi/ne4kfy6/?context=3
r/FastAPI • u/[deleted] • Aug 14 '25
Hey guys, been enjoying fastapi for a bit now. How much do you use lifespan on fastapi and on what purposes have you used it on?
18 comments sorted by
View all comments
1
I use it like this:
class AppState(TypedDict): """ Defines the structure of the shared state during the application lifecycle. This provides explicit type information for type checkers and editors. """ engine: AsyncEngine session_factory: async_sessionmaker[AsyncSession] @asynccontextmanager async def lifespan(app: FastAPI) -> AsyncIterator[AppState]: # -------- Startup -------- get_settings() engine, session_factory = await setup_database_connection() logger.info("🚀 Application started, database is ready.") await create_db_and_tables(engine) # yield {"engine": engine, "session_factory": session_factory} # More type-safe approach yield AppState( engine=engine, session_factory=session_factory, ) # -------- Shutdown -------- await close_database_connection(engine) logger.info("Application shut down, resources released.")
View all comments
1
u/leec0621 Sep 14 '25
I use it like this: