mirror of
https://github.com/fastapi/sqlmodel.git
synced 2025-08-15 10:11:34 +08:00
✨ Add source examples for docs
This commit is contained in:
60
docs_src/tutorial/fastapi/multiple_models/tutorial001.py
Normal file
60
docs_src/tutorial/fastapi/multiple_models/tutorial001.py
Normal file
@ -0,0 +1,60 @@
|
||||
from typing import List, Optional
|
||||
|
||||
from fastapi import FastAPI
|
||||
from sqlmodel import Field, Session, SQLModel, create_engine, select
|
||||
|
||||
|
||||
class Hero(SQLModel, table=True):
|
||||
id: Optional[int] = Field(default=None, primary_key=True)
|
||||
name: str
|
||||
secret_name: str
|
||||
age: Optional[int] = None
|
||||
|
||||
|
||||
class HeroCreate(SQLModel):
|
||||
name: str
|
||||
secret_name: str
|
||||
age: Optional[int] = None
|
||||
|
||||
|
||||
class HeroRead(SQLModel):
|
||||
id: int
|
||||
name: str
|
||||
secret_name: str
|
||||
age: Optional[int] = None
|
||||
|
||||
|
||||
sqlite_file_name = "database.db"
|
||||
sqlite_url = f"sqlite:///{sqlite_file_name}"
|
||||
|
||||
connect_args = {"check_same_thread": False}
|
||||
engine = create_engine(sqlite_url, echo=True, connect_args=connect_args)
|
||||
|
||||
|
||||
def create_db_and_tables():
|
||||
SQLModel.metadata.create_all(engine)
|
||||
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
|
||||
@app.on_event("startup")
|
||||
def on_startup():
|
||||
create_db_and_tables()
|
||||
|
||||
|
||||
@app.post("/heroes/", response_model=HeroRead)
|
||||
def create_hero(hero: HeroCreate):
|
||||
with Session(engine) as session:
|
||||
db_hero = Hero.from_orm(hero)
|
||||
session.add(db_hero)
|
||||
session.commit()
|
||||
session.refresh(db_hero)
|
||||
return db_hero
|
||||
|
||||
|
||||
@app.get("/heroes/", response_model=List[HeroRead])
|
||||
def read_heroes():
|
||||
with Session(engine) as session:
|
||||
heroes = session.exec(select(Hero)).all()
|
||||
return heroes
|
Reference in New Issue
Block a user