Bird
0
0

What is wrong with this SQLAlchemy session management in FastAPI?

medium📝 Debug Q7 of 15
FastAPI - Database Integration
What is wrong with this SQLAlchemy session management in FastAPI?
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

@app.get('/items')
def read_items(db: Session = Depends(get_db)):
    return db.query(Item).all()
AThe function get_db should not use yield.
BThe session is not closed properly.
CDepends should use get_db without parentheses.
DSessionLocal is not imported or defined.
Step-by-Step Solution
Solution:
  1. Step 1: Check if SessionLocal is defined or imported

    SessionLocal must be defined or imported before use; otherwise, this code will raise a NameError.
  2. Step 2: Validate other parts

    Using yield in get_db is correct for dependency injection. Depends(get_db) is correct usage. The session is closed in finally block properly.
  3. Final Answer:

    SessionLocal is not imported or defined. -> Option D
  4. Quick Check:

    SessionLocal must be defined before use [OK]
Quick Trick: Always import or define SessionLocal before use [OK]
Common Mistakes:
MISTAKES
  • Forgetting to import SessionLocal
  • Misusing yield in dependency
  • Incorrect Depends syntax

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes