-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
48 lines (36 loc) · 1.24 KB
/
app.py
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
import os
from typing import Optional
from fastapi import FastAPI
from sqlmodel import Field, SQLModel, select
from sqlmodel.ext.asyncio.session import AsyncSession
from sqlalchemy.ext.asyncio import create_async_engine
sqlite_file_name = os.environ["SQLITE_FILE_DB_PATH"]
sqlite_url = f"sqlite+aiosqlite:///{sqlite_file_name}"
connect_args = {"check_same_thread": False}
engine = create_async_engine(
sqlite_url, future=True, echo=True, connect_args=connect_args
)
class Hero(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
secret_name: str
age: Optional[int] = None
app = FastAPI()
@app.on_event("startup")
async def startup():
# create db tables
async with engine.begin() as conn:
await conn.run_sync(SQLModel.metadata.drop_all)
await conn.run_sync(SQLModel.metadata.create_all)
@app.post("/heroes/")
async def create_hero(hero: Hero):
async with AsyncSession(engine) as session:
session.add(hero)
await session.commit()
await session.refresh(hero)
return hero
@app.get("/heroes/")
async def read_heroes():
async with AsyncSession(engine) as session:
heroes = await session.exec(select(Hero))
return heroes.all()