Bird
0
0

You need to create a shared dependency in FastAPI that provides a database session and ensures the session is closed after the request completes. Which implementation correctly achieves this?

hard🚀 Application Q8 of 15
FastAPI - Dependency Injection
You need to create a shared dependency in FastAPI that provides a database session and ensures the session is closed after the request completes. Which implementation correctly achieves this?
AUse a dependency function with <code>yield</code> to provide the session and close it after yielding
BReturn the session object directly without cleanup logic
CCreate the session inside the route handler and close it manually
DUse a global session object shared across all requests without closing
Step-by-Step Solution
Solution:
  1. Step 1: Use yield in dependency

    FastAPI supports dependencies with yield to provide setup and teardown logic.
  2. Step 2: Provide session and cleanup

    The dependency yields the session, then closes it after the request finishes.
  3. Step 3: Avoid global or manual closing

    Global sessions or manual closing inside routes can cause concurrency issues or leaks.
  4. Final Answer:

    Use a dependency function with yield to provide the session and close it after yielding -> Option A
  5. Quick Check:

    Yield-based dependencies handle cleanup automatically [OK]
Quick Trick: Use yield in dependencies for setup and teardown [OK]
Common Mistakes:
MISTAKES
  • Not closing sessions causing resource leaks
  • Using global sessions shared unsafely
  • Closing sessions manually inside routes

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes