Skip to content

Commit db16e11

Browse files
authored
Update Docs - FastAPI on_startup method to lifespan
1 parent 74feaa5 commit db16e11

File tree

2 files changed

+6
-4
lines changed

2 files changed

+6
-4
lines changed

docs/tutorial/fastapi/simple-hero-api.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,7 @@ We want to make sure that once the app starts running, the function `create_tabl
6464

6565
This should be called only once at startup, not before every request, so we put it in the function to handle the `"startup"` event:
6666

67-
{* ./docs_src/tutorial/fastapi/simple_hero_api/tutorial001_py310.py ln[23:28] hl[26:28] *}
67+
{* ./docs_src/tutorial/fastapi/simple_hero_api/tutorial001_py310.py ln[24:30] hl[27:30] *}
6868

6969
## Create Heroes *Path Operation*
7070

docs_src/tutorial/fastapi/simple_hero_api/tutorial001_py310.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
from fastapi import FastAPI
22
from sqlmodel import Field, Session, SQLModel, create_engine, select
3+
from contextlib import asynccontextmanager
34

45

56
class Hero(SQLModel, table=True):
@@ -20,12 +21,13 @@ def create_db_and_tables():
2021
SQLModel.metadata.create_all(engine)
2122

2223

23-
app = FastAPI()
24+
app = FastAPI(lifespan=lifespan)
2425

2526

26-
@app.on_event("startup")
27-
def on_startup():
27+
@asynccontextmanager
28+
async def lifespan(app: FastAPI):
2829
create_db_and_tables()
30+
yield
2931

3032

3133
@app.post("/heroes/")

0 commit comments

Comments
 (0)