Complete the code to define a FastAPI app with a startup event handler.
from fastapi import FastAPI app = FastAPI() @app.on_event("[1]") async def startup_event(): print("App is starting up")
The correct decorator for startup events in FastAPI is @app.on_event("startup"). Here, the blank is filled with startup.
Complete the code to define a shutdown event handler in FastAPI.
from fastapi import FastAPI app = FastAPI() @app.on_event("[1]") async def shutdown_event(): print("App is shutting down")
The correct event name for shutdown in FastAPI is "shutdown". This decorator runs the function when the app is closing.
Fix the error in the code to properly close a database connection on shutdown.
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()
The shutdown event must be named "shutdown" to properly register the close_db function to run when the app stops.
Fill both blanks to create a dependency that opens and closes a database connection per request.
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()
The database connection should be closed with close() in the finally block. The dependency function is get_db, which is passed to Depends.
Fill all three blanks to create a FastAPI app that manages a resource with startup and shutdown events and a route using that resource.
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]()
The startup event is named "startup", the shutdown event is "shutdown", and the resource is closed with close().