Consider a FastAPI app using a lifespan context manager to open and close a database connection. What is the correct sequence of events when the app starts and stops?
from fastapi import FastAPI from contextlib import asynccontextmanager @asynccontextmanager async def lifespan(app: FastAPI): print('Connecting to DB') yield print('Disconnecting from DB') app = FastAPI(lifespan=lifespan)
Think about what happens before and after the yield statement in a context manager.
The code before yield runs when the app starts, and the code after yield runs when the app stops.
Given this FastAPI app with a lifespan context manager, what will be printed to the console when the app starts and then stops?
from fastapi import FastAPI from contextlib import asynccontextmanager @asynccontextmanager async def lifespan(app: FastAPI): print('Starting app') yield print('Stopping app') app = FastAPI(lifespan=lifespan)
Remember the lifespan context manager runs code before and after the yield.
The print before yield runs at startup, the print after yield runs at shutdown.
Examine this lifespan context manager code. Why does it raise a RuntimeError when the app starts?
from fastapi import FastAPI from contextlib import asynccontextmanager @asynccontextmanager async def lifespan(app: FastAPI): print('Setup') # Missing yield statement print('Teardown') app = FastAPI(lifespan=lifespan)
Async context managers must have exactly one yield.
Without a yield, the async context manager is invalid and raises RuntimeError.
Choose the option with correct syntax for an async lifespan context manager in FastAPI.
FastAPI expects an async context manager with the app parameter.
Option C uses asynccontextmanager decorator, async function with app parameter, and yield.
Why would a developer use a lifespan context manager in a FastAPI application?
Think about what happens when the app starts and stops.
Lifespan context managers allow running code at app startup and shutdown to manage resources.