Recall & Review
beginner
What is the purpose of the lifespan context manager in FastAPI?
It manages startup and shutdown events for the application, allowing you to run code before the app starts and after it stops.
Click to reveal answer
intermediate
How do you define a lifespan context manager in FastAPI?
By creating an async generator function that yields control once startup tasks are done, then runs shutdown tasks after the yield.
Click to reveal answer
beginner
Which FastAPI parameter accepts the lifespan context manager?
The 'lifespan' parameter in the FastAPI constructor accepts the lifespan context manager function.
Click to reveal answer
intermediate
What happens if you don't use a lifespan context manager in FastAPI?
You cannot run custom startup or shutdown code automatically; you would need to use event decorators or miss lifecycle control.
Click to reveal answer
beginner
Show a simple example of a lifespan context manager in FastAPI.
from fastapi import FastAPI
from contextlib import asynccontextmanager
@asynccontextmanager
async def lifespan(app):
print('Starting up')
yield
print('Shutting down')
app = FastAPI(lifespan=lifespan)Click to reveal answer
What type of function is used to create a lifespan context manager in FastAPI?
✗ Incorrect
The lifespan context manager must be an async generator function that yields control to manage startup and shutdown.
Where do you pass the lifespan context manager in FastAPI?
✗ Incorrect
You pass the lifespan context manager function as the 'lifespan' parameter when creating the FastAPI app instance.
What does the yield statement do inside the lifespan context manager?
✗ Incorrect
The yield pauses the startup code and lets FastAPI run the app; after the app stops, the code after yield runs for shutdown.
Which of these is NOT a benefit of using a lifespan context manager?
✗ Incorrect
Lifespan context managers help with startup/shutdown tasks, not directly with HTTP response speed.
If you want to connect to a database on startup and disconnect on shutdown, where should you put this code?
✗ Incorrect
The lifespan context manager is the right place to open and close resources like database connections.
Explain how the lifespan context manager controls startup and shutdown in FastAPI.
Think about what happens before and after the yield in the async function.
You got /5 concepts.
Describe a real-life scenario where using a lifespan context manager in FastAPI is helpful.
Imagine preparing and cleaning up before and after a big event.
You got /5 concepts.