Which of the following code snippets correctly defines a FastAPI dependency that yields a SQLAlchemy database session?
easy📝 Syntax Q3 of 15
FastAPI - Database Integration
Which of the following code snippets correctly defines a FastAPI dependency that yields a SQLAlchemy database session?
Adef get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
Bdef get_db():
db = SessionLocal()
return db
db.close()
Cdef get_db():
db = SessionLocal()
yield db
db.commit()
Ddef get_db():
db = SessionLocal()
db.close()
yield db
Step-by-Step Solution
Solution:
Step 1: Review proper session management
The session must be yielded inside a try block and closed in the finally block to ensure closure even if exceptions occur.
Step 2: Analyze options
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close() correctly uses try-finally with yield; others either close before yield or miss finally.
Final Answer:
Option A -> Option A
Quick Check:
Yield inside try, close in finally ensures proper cleanup [OK]
Quick Trick:Use try-finally with yield for session dependencies [OK]
Common Mistakes:
MISTAKES
Closing session before yielding
Returning session without yield
Calling commit instead of close in finally
Master "Database Integration" in FastAPI
9 interactive learning modes - each teaches the same concept differently