0
0
FastAPIframework~10 mins

Connection lifecycle management 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 a FastAPI app with a startup event handler.

FastAPI
from fastapi import FastAPI

app = FastAPI()

@app.on_event("[1]")
async def startup_event():
    print("App is starting up")
Drag options to blanks, or click blank then click option'
Astartup
Bon_startup
Con_start
Dstart
Attempts:
3 left
💡 Hint
Common Mistakes
Using incorrect event names like 'start' or 'on_start'.
Forgetting to use the @app.on_event decorator.
2fill in blank
medium

Complete the code to define a shutdown event handler in FastAPI.

FastAPI
from fastapi import FastAPI

app = FastAPI()

@app.on_event("[1]")
async def shutdown_event():
    print("App is shutting down")
Drag options to blanks, or click blank then click option'
Astop
Bstart
Cshutdown
Dclose
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'stop' or 'close' instead of 'shutdown'.
Not using the @app.on_event decorator.
3fill in blank
hard

Fix the error in the code to properly close a database connection on shutdown.

FastAPI
from fastapi import FastAPI

app = FastAPI()
db = None

@app.on_event("startup")
async def connect_db():
    global db
    db = await connect_to_db()

@app.on_event("[1]")
async def close_db():
    await db.close()
Drag options to blanks, or click blank then click option'
Astart
Bclose
Cstop
Dshutdown
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'close' or 'stop' instead of 'shutdown'.
Not awaiting the close method.
4fill in blank
hard

Fill both blanks to create a dependency that opens and closes a database connection per request.

FastAPI
from fastapi import FastAPI, Depends

app = FastAPI()

async def get_db():
    db = await connect_to_db()
    try:
        yield db
    finally:
        await db.[1]()

@app.get("/items")
async def read_items(db = Depends([2])):
    return await db.fetch_items()
Drag options to blanks, or click blank then click option'
Aclose
Bconnect
Cget_db
Ddisconnect
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'disconnect' instead of 'close'.
Passing 'connect' instead of the dependency function to Depends.
5fill in blank
hard

Fill all three blanks to create a FastAPI app that manages a resource with startup and shutdown events and a route using that resource.

FastAPI
from fastapi import FastAPI

app = FastAPI()
resource = None

@app.on_event("[1]")
async def startup():
    global resource
    resource = await open_resource()

@app.on_event("[2]")
async def shutdown():
    await resource.[3]()
Drag options to blanks, or click blank then click option'
Astartup
Bshutdown
Cclose
Dopen
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up event names.
Using 'open' instead of 'close' to release the resource.