Bird
0
0

How can you combine FastAPI lifespan context manager with a third-party async library that requires explicit startup and shutdown calls?

hard🚀 Application Q9 of 15
FastAPI - Middleware and Hooks
How can you combine FastAPI lifespan context manager with a third-party async library that requires explicit startup and shutdown calls?
Aasync def lifespan(app: FastAPI):\n await third_party.startup()\n yield\n await third_party.shutdown()
Bdef lifespan(app: FastAPI):\n third_party.startup()\n yield\n third_party.shutdown()
Casync def lifespan():\n await third_party.startup()\n yield\n await third_party.shutdown()
Dasync def lifespan(app: FastAPI):\n third_party.startup()\n yield\n third_party.shutdown()
Step-by-Step Solution
Solution:
  1. Step 1: Use async def and await for async third-party calls

    Third-party startup and shutdown are async, so await is required.
  2. Step 2: Accept app parameter for lifespan signature

    Lifespan must accept app parameter even if unused.
  3. Final Answer:

    async def lifespan(app: FastAPI):\n await third_party.startup()\n yield\n await third_party.shutdown() -> Option A
  4. Quick Check:

    Async lifespan with await and app parameter [OK]
Quick Trick: Await async startup/shutdown inside lifespan [OK]
Common Mistakes:
MISTAKES
  • Missing async/await
  • Omitting app parameter
  • Using sync calls for async functions

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More FastAPI Quizzes