new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

FastAPI · Advanced · all subjects

lifespan events

15 notes, read out of this brain and free to use. Each one was extracted from a source and is re-checked against its exam.

Lifespan events overview

FastAPI allows you to define logic that executes before the application starts receiving requests (startup) and after it finishes handling all requests (shutdown). These are executed once each during the application lifespan. Startup code runs before the application begins serving requests, and shutdown code runs after all requests have been handled.

Lifespan parameter and async context manager

The `lifespan` parameter of the FastAPI app accepts an async context manager. You create this using an async function decorated with `@asynccontextmanager` from the contextlib module. The function uses `yield` to separate startup code (before yield) from shutdown code (after yield).

Lifespan function execution pattern

A lifespan function is an async function decorated with `@asynccontextmanager`. Code before the `yield` statement executes before the application starts taking requests. Code after the `yield` statement executes after the application finishes handling requests.

Async context manager usage

An async context manager is used with `async with` syntax. Before entering the `with` block, code before `yield` executes. After exiting the `with` block, code after `yield` executes. FastAPI receives the async context manager via the `lifespan` parameter and manages its lifecycle automatically.

Deprecated startup and shutdown events

The alternative way to handle startup and shutdown uses `@app.on_event('startup')` and `@app.on_event('shutdown')` decorators. These are deprecated in favor of the `lifespan` parameter. If you provide a `lifespan` parameter, the startup and shutdown event handlers will no longer be called; you must use either lifespan or events, not both.

Startup event handler

The startup event handler is declared with `@app.on_event('startup')`. It runs before the application starts receiving requests. Multiple startup event handlers can be added, and the application will not start receiving requests until all startup handlers complete. These can be defined with `async def` or normal `def`.

Shutdown event handler

The shutdown event handler is declared with `@app.on_event('shutdown')`. It runs when the application is shutting down, after all requests have been handled. These can be defined with `async def` or normal `def`.

Use case: loading expensive resources at startup

Lifespan events are useful for loading resources before the application starts that are shared among all requests and would be expensive to load per-request. For example, machine learning models, database connection pools, or other shared resources that take significant time to initialize. Loading at startup avoids the cost of reloading for every request and avoids loading during module import or tests.

Resource cleanup in shutdown

The shutdown phase of lifespan events is used to clean up resources acquired during startup, such as releasing memory, closing database connections, or freeing GPU resources.

Lifespan state sharing between startup and shutdown

Using `lifespan` as a single function with `yield` allows startup and shutdown logic to share variables and state more easily than using separate startup and shutdown event handlers. This is the recommended approach because it keeps related logic together.

Lifespan events not executed for sub-applications

Lifespan events (startup and shutdown) are only executed for the main application, not for sub-applications that are mounted using the mount functionality.

Async def vs def in event handlers

Event handler functions can be declared with either `async def` or normal `def`. Use `async def` when the handler needs to perform async operations, and use normal `def` when it only performs synchronous I/O operations.

TestClient with statement for lifespan testing

To run lifespan events during tests, use TestClient with a with statement. This allows lifespan context managers to execute properly in the testing environment.

TestClient for deprecated startup and shutdown events

For the deprecated startup and shutdown events, TestClient can be used directly without requiring a with statement.

Lifespan testing reference

Running lifespan in tests is documented in the official Starlette documentation at https://starlette.dev/lifespan/#running-lifespan-in-tests

Give your agent this brain