Bird
0
0

How can you use Depends to share a database session across multiple routes without repeating code? Choose the best approach.

hard🚀 Application Q15 of 15
FastAPI - Dependency Injection
How can you use Depends to share a database session across multiple routes without repeating code? Choose the best approach.
AUse Depends without any function to automatically get the session
BPass the session as a global variable to all routes
CManually create a session inside each route function
DCreate a function that returns the session and use Depends on it in each route
Step-by-Step Solution
Solution:
  1. Step 1: Understand code reuse with Depends

    Depends allows you to write a function that creates or yields a database session once and injects it wherever needed.
  2. Step 2: Identify the best practice

    Creating a session function and using Depends on it in routes avoids repetition and manages session lifecycle cleanly.
  3. Final Answer:

    Create a function that returns the session and use Depends on it in each route -> Option D
  4. Quick Check:

    Use Depends with session function for reuse = D [OK]
Quick Trick: Use Depends with a session function to share DB session [OK]
Common Mistakes:
MISTAKES
  • Using global variables for sessions (not safe)
  • Creating sessions manually in every route (repetitive)
  • Using Depends without specifying a function

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes