Complete the code to define an async generator dependency in FastAPI.
async def get_db(): db = connect_to_db() try: yield [1] finally: db.close()
The async generator yields the database connection object db so it can be used by the route handler.
Complete the code to use the async generator dependency in a FastAPI route.
from fastapi import Depends, FastAPI app = FastAPI() @app.get("/items/") async def read_items(db = Depends([1])): return {"db_status": str(db)}
The route uses Depends(get_db) to inject the async generator dependency.
Fix the error in the async generator dependency by completing the code.
async def get_session(): session = create_session() try: [1] session finally: await session.close()
Async generator dependencies must use yield to provide the resource.
Fill both blanks to correctly define and use an async generator dependency with FastAPI.
async def get_resource(): resource = await acquire_resource() try: [1] resource finally: await [2]
The async generator yields the resource and then releases it asynchronously in the finally block.
Fill all three blanks to create a FastAPI route that depends on two async generator dependencies.
async def get_db(): db = connect_db() try: [1] db finally: db.close() async def get_cache(): cache = await connect_cache() try: [2] cache finally: await cache.disconnect() @app.get("/data/") async def get_data(db = Depends([3]), cache = Depends(get_cache)): return {"db": str(db), "cache": str(cache)}
Both async generators use yield to provide resources. The route depends on get_db and get_cache.