Bird
0
0

Consider this FastAPI route using a database session dependency: ```python def get_db(): db = SessionLocal() try: yield db finally: db.close() @app.get('/products/{product_id}') async def read_product(product_id: int, db: Session = Depends(get_db)): product = db.query(Product).filter(Product.id == product_id).first() return product ``` What will happen if the database session is managed as shown?

medium📝 component behavior Q4 of 15
FastAPI - Database Integration
Consider this FastAPI route using a database session dependency: ```python def get_db(): db = SessionLocal() try: yield db finally: db.close() @app.get('/products/{product_id}') async def read_product(product_id: int, db: Session = Depends(get_db)): product = db.query(Product).filter(Product.id == product_id).first() return product ``` What will happen if the database session is managed as shown?
AThe product will be fetched correctly and the session will close after the request
BThe session will remain open causing a connection leak
CThe product query will fail because the session is closed before querying
DThe endpoint will raise an exception due to missing commit
Step-by-Step Solution
Solution:
  1. Step 1: Understand session lifecycle

    The session is yielded for use in the route and closed in the finally block after the request completes.
  2. Step 2: Analyze behavior

    The query executes while the session is active, so the product is fetched correctly.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Yielded session is active during request, closed after [OK]
Quick Trick: Session active during yield, closed after request [OK]
Common Mistakes:
MISTAKES
  • Assuming session closes before query
  • Expecting commit for read-only queries
  • Believing session leaks if finally used

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes