0
0
FastAPIframework~5 mins

Lifespan context manager in FastAPI - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
AA regular synchronous function
BAn async generator function
CA class constructor
DA lambda function
Where do you pass the lifespan context manager in FastAPI?
AAs the 'lifespan' argument in FastAPI()
BInside a route decorator
CIn the middleware configuration
DIn the database connection setup
What does the yield statement do inside the lifespan context manager?
AStarts the server
BEnds the function immediately
CPauses startup and waits for shutdown
DRuns the main application code
Which of these is NOT a benefit of using a lifespan context manager?
AFaster HTTP response times
BCentralized startup and shutdown logic
CAutomatic resource cleanup
DCleaner code organization
If you want to connect to a database on startup and disconnect on shutdown, where should you put this code?
AIn the main.py global scope
BInside a route handler
CIn the HTML templates
DInside the lifespan context manager
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.