Bird
0
0

Identify the error in this FastAPI database session management code:

medium📝 Debug Q14 of 15
FastAPI - Database Integration
Identify the error in this FastAPI database session management code:
def get_db():
    db = Session()
    yield db
    db.close()

@app.post('/add')
def add_item(item: Item, db: Session = Depends(get_db)):
    db.add(item)
    db.commit()
AThe <code>item</code> parameter should be inside <code>get_db</code>
BThe session is closed after yield, so it may not close if an exception occurs
CThe <code>Depends</code> is used incorrectly in the route
DThe <code>db.commit()</code> is missing
Step-by-Step Solution
Solution:
  1. Step 1: Review session closing in get_db

    The db.close() is called after yield without a try-finally block, so if an exception happens, the session may never close.
  2. Step 2: Understand proper session cleanup

    Using try-finally ensures the session closes even if errors occur during request handling.
  3. Final Answer:

    The session is closed after yield, so it may not close if an exception occurs -> Option B
  4. Quick Check:

    Session close needs try-finally for safety [OK]
Quick Trick: Always use try-finally to close sessions safely [OK]
Common Mistakes:
MISTAKES
  • Ignoring try-finally for session cleanup
  • Forgetting to commit changes
  • Misplacing Depends usage

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes