-
Notifications
You must be signed in to change notification settings - Fork 106
Expand file tree
/
Copy pathapp.py
More file actions
51 lines (33 loc) · 1.13 KB
/
app.py
File metadata and controls
51 lines (33 loc) · 1.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
from collections.abc import AsyncIterator, Sequence
from contextlib import asynccontextmanager
from fastapi import FastAPI
from sqlmodel import Field, Session, SQLModel, create_engine, select
from config import settings
class Hero(SQLModel, table=True):
id: int | None = Field(default=None, primary_key=True)
name: str = Field(index=True)
secret_name: str
age: int | None = Field(default=None, index=True)
engine = create_engine(str(settings.SQLALCHEMY_DATABASE_URI))
def create_db_and_tables() -> None:
SQLModel.metadata.create_all(engine)
@asynccontextmanager
async def lifespan(_app: FastAPI) -> AsyncIterator[None]:
create_db_and_tables()
yield
app = FastAPI(lifespan=lifespan)
@app.get("/")
def hello() -> str:
return "Hello, Docker!"
@app.post("/heroes/")
def create_hero(hero: Hero) -> Hero:
with Session(engine) as session:
session.add(hero)
session.commit()
session.refresh(hero)
return hero
@app.get("/heroes/")
def read_heroes() -> Sequence[Hero]:
with Session(engine) as session:
heroes = session.exec(select(Hero)).all()
return heroes