Hint: Use yield, not return, to run shutdown code [OK]
Common Mistakes:
Confusing return and yield in async functions
Ignoring that shutdown code runs after yield
Assuming print statements cause errors
5. You want to open a database connection when your FastAPI app starts and close it when the app stops using the lifespan context manager. Which code correctly implements this?
hard
A. async def lifespan(app):
db = await connect_db()
app.state.db = db
yield
await db.close()
B. async def lifespan(app):
db = await connect_db()
yield
app.state.db = db
await db.close()
C. def lifespan(app):
db = connect_db()
app.state.db = db
yield
db.close()
D. async def lifespan():
db = await connect_db()
app.state.db = db
yield
await db.close()
Solution
Step 1: Confirm async function with app parameter
The lifespan function must be async and accept the app parameter to store the db connection.
Step 2: Check order of operations
Connect to the database before yield, store it on app.state, then close it after yield.
Step 3: Verify correct use of await and yield
Await connect_db and db.close, yield separates startup and shutdown code.
Final Answer:
async def lifespan(app):
db = await connect_db()
app.state.db = db
yield
await db.close() -> Option A