0
0
FastAPIframework~10 mins

Async generator dependencies in FastAPI - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define an async generator dependency in FastAPI.

FastAPI
async def get_db():
    db = connect_to_db()
    try:
        yield [1]
    finally:
        db.close()
Drag options to blanks, or click blank then click option'
Adb
Bconnect_to_db()
Cawait db
Ddb.close()
Attempts:
3 left
💡 Hint
Common Mistakes
Yielding the function call instead of the connection object.
Calling close() before yielding.
2fill in blank
medium

Complete the code to use the async generator dependency in a FastAPI route.

FastAPI
from fastapi import Depends, FastAPI

app = FastAPI()

@app.get("/items/")
async def read_items(db = Depends([1])):
    return {"db_status": str(db)}
Drag options to blanks, or click blank then click option'
Aconnect_to_db
Bget_db
Cdb.close
Dyield_db
Attempts:
3 left
💡 Hint
Common Mistakes
Using the connection function instead of the dependency function.
Trying to call the dependency instead of passing it to Depends.
3fill in blank
hard

Fix the error in the async generator dependency by completing the code.

FastAPI
async def get_session():
    session = create_session()
    try:
        [1] session
    finally:
        await session.close()
Drag options to blanks, or click blank then click option'
Aawait
Breturn
Cyield from
Dyield
Attempts:
3 left
💡 Hint
Common Mistakes
Using return instead of yield in async generator.
Using await incorrectly before yield.
4fill in blank
hard

Fill both blanks to correctly define and use an async generator dependency with FastAPI.

FastAPI
async def get_resource():
    resource = await acquire_resource()
    try:
        [1] resource
    finally:
        await [2]
Drag options to blanks, or click blank then click option'
Ayield
Brelease_resource()
Cresource.close()
Dreturn
Attempts:
3 left
💡 Hint
Common Mistakes
Using return instead of yield.
Calling close() instead of the async release function.
5fill in blank
hard

Fill all three blanks to create a FastAPI route that depends on two async generator dependencies.

FastAPI
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)}
Drag options to blanks, or click blank then click option'
Ayield
Cget_db
Dreturn
Attempts:
3 left
💡 Hint
Common Mistakes
Using return instead of yield in generators.
Passing the wrong function to Depends.