Bird
0
0

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:
  1. 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.
  2. 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.
  3. Final Answer:

    Option A -> Option A
  4. 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

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes