[Issue #1312]: full examples use lifespan instead of on_startup (#1363)

* docs(examples): full examples use lifespan instead of on_startup for database initialization

* Update beanie.md

Replaced the annotations on the notes that I missed
This commit is contained in:
Brandon H. Goding
2024-03-05 03:09:49 -05:00
committed by GitHub
parent 0df82afb32
commit 2ffb7006ff
5 changed files with 60 additions and 39 deletions

View File

@ -40,20 +40,24 @@ Notice that we pass a reference to the `User` model we defined above.
## Initialize Beanie
When initializing your FastAPI app, it's important that you [**initialize Beanie**](https://roman-right.github.io/beanie/tutorial/initialization/) so it can discover your models. We can achieve this using a startup event handler on the FastAPI app:
When initializing your FastAPI app, it's important that you [**initialize Beanie**](https://roman-right.github.io/beanie/tutorial/initialization/) so it can discover your models. We can achieve this using [**Lifespan Events**](https://fastapi.tiangolo.com/advanced/events/) on the FastAPI app:
```py
from contextlib import asynccontextmanager
from beanie import init_beanie
@app.on_event("startup")
async def on_startup():
@asynccontextmanager
async def lifespan(app: FastAPI):
await init_beanie(
database=db, # (1)!
document_models=[
User, # (2)!
],
)
yield
app = FastAPI(lifespan=lifespan)
```
1. This is the `db` Motor database instance we defined above.