Bird
0
0

You want to implement a FastAPI dependency that yields a database session and ensures it is closed after the request completes. Which implementation is correct?

hard🚀 Application Q8 of 15
FastAPI - Dependency Injection
You want to implement a FastAPI dependency that yields a database session and ensures it is closed after the request completes. Which implementation is correct?
AUse a generator function with yield and close session after yield
BReturn the session directly without closing it
CCreate a global session object and reuse it
DOpen and close the session inside the path operation function
Step-by-Step Solution
Solution:
  1. Step 1: Understand resource management

    Database sessions should be opened per request and closed after to avoid leaks.
  2. Step 2: Use generator dependencies

    FastAPI supports dependencies as generators using yield to provide the resource and then run cleanup code after the request.
  3. Step 3: Correct pattern

    Define a dependency function that creates the session, yields it, and then closes it after the yield.
  4. Final Answer:

    Use a generator function with yield and close session after yield -> Option A
  5. Quick Check:

    Yield dependencies allow cleanup after request [OK]
Quick Trick: Use yield in dependency to manage resource lifecycle [OK]
Common Mistakes:
MISTAKES
  • Not closing sessions leading to resource leaks
  • Using global sessions causing concurrency issues
  • Managing sessions manually inside path operations

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes