Content Index
Lifespan is a mechanism based on a ContextManager that allows us to execute code just before the application starts or after it ends.
Previously, we saw how to declare example Request data in FastAPI, let's look at a more advanced aspect.
Context Manager Implementation
Its use is simple and employs the @asynccontextmanager decorator. As we did with the database, we will use the yield keyword.
Everything before the yield will be executed when the server starts.
Everything after the yield will be executed when the server shuts down (for example, to close connections or clean up files).
Automatic Data Creation (Seed): Preparing Rooms for WebSockets
I have created a function that is responsible for "populating" the rooms. The flow is as follows:
- When starting the app, we verify if the rooms already exist in the database.
- If they are not created, we iterate a predefined list and insert the records.
- We execute the commit to save the changes and close the session.[2]
Configuration in the application
To activate this behavior, we must pass the lifespan parameter when instantiating FastAPI, leaving the code as:
api_multiple.py
from contextlib import asynccontextmanager
***
def create_rooms():
db = SessionLocal()
try:
for name in ["room 1", "room 2"]:
if not db.query(models.Room).filter(models.Room.name == name).first():
db.add(models.Room(name=name))
db.commit()
finally:
db.close()
@asynccontextmanager
async def lifespan(app: FastAPI):
print('****START')
create_rooms()
yield
print('****END')
app = FastAPI(lifespan=lifespan)
router = APIRouter()Deprecated lifecycle methods
If you review old documentation, you may find the decorators @app.on_event("startup") and @app.on_event("shutdown"). It is important to know that these events are deprecated.[3][4]
Although they still work, the community and FastAPI developers recommend using lifespan exclusively, as it is more flexible and allows managing the lifecycle in a more integrated way in a single block of code.
Conclusion
This data initialization mechanism is ideal for real projects where certain static values (such as roles, categories or rooms) must be available from the first second without the need to create additional user interfaces to load them.
With the rooms automatically generated, we are ready to move on to the next phase.
The next step is to learn how to implement Clean Code principles in a FastAPI app.