Bird
0
0

Which of the following get_db implementations best achieves this?

hard🚀 Application Q15 of 15
FastAPI - Database Integration
You want to ensure that your FastAPI app's database sessions are properly managed and that any changes are committed only if no exceptions occur. Which of the following get_db implementations best achieves this?
Adef get_db(): db = Session() try: yield db db.commit() except: db.rollback() raise finally: db.close()
Bdef get_db(): db = Session() yield db db.commit() db.close()
Cdef get_db(): db = Session() try: yield db finally: db.close()
Ddef get_db(): db = Session() yield db db.rollback() db.close()
Step-by-Step Solution
Solution:
  1. Step 1: Understand transaction management needs

    We want to commit changes only if no errors occur, otherwise rollback to avoid partial changes.
  2. Step 2: Analyze each get_db implementation

    def get_db(): db = Session() try: yield db db.commit() except: db.rollback() raise finally: db.close() uses try-except-finally to commit on success, rollback on error, and always close the session, which is the safest approach.
  3. Final Answer:

    def get_db(): db = Session() try: yield db db.commit() except: db.rollback() raise finally: db.close() -> Option A
  4. Quick Check:

    Commit on success, rollback on error, always close [OK]
Quick Trick: Use try-except-finally to commit, rollback, and close sessions [OK]
Common Mistakes:
MISTAKES
  • Committing after yield without error handling
  • Not rolling back on exceptions
  • Closing session without try-finally

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes