Coverage for docs_src/tutorial/fastapi/multiple_models/tutorial001_py310.py: 100%
39 statements
« prev ^ index » next coverage.py v7.6.1, created at 2024-09-09 00:02 +0000
« prev ^ index » next coverage.py v7.6.1, created at 2024-09-09 00:02 +0000
1from fastapi import FastAPI 1abc
2from sqlmodel import Field, Session, SQLModel, create_engine, select 1abc
5class Hero(SQLModel, table=True): 1abc
6 id: int | None = Field(default=None, primary_key=True) 1abc
7 name: str = Field(index=True) 1abc
8 secret_name: str 1abc
9 age: int | None = Field(default=None, index=True) 1abc
12class HeroCreate(SQLModel): 1abc
13 name: str 1abc
14 secret_name: str 1abc
15 age: int | None = None 1abc
18class HeroPublic(SQLModel): 1abc
19 id: int 1abc
20 name: str 1abc
21 secret_name: str 1abc
22 age: int | None = None 1abc
25sqlite_file_name = "database.db" 1abc
26sqlite_url = f"sqlite:///{sqlite_file_name}" 1abc
28connect_args = {"check_same_thread": False} 1abc
29engine = create_engine(sqlite_url, echo=True, connect_args=connect_args) 1abc
32def create_db_and_tables(): 1abc
33 SQLModel.metadata.create_all(engine) 1abc
36app = FastAPI() 1abc
39@app.on_event("startup") 1abc
40def on_startup(): 1abc
41 create_db_and_tables() 1abc
44@app.post("/heroes/", response_model=HeroPublic) 1abc
45def create_hero(hero: HeroCreate): 1abc
46 with Session(engine) as session: 1abc
47 db_hero = Hero.model_validate(hero) 1abc
48 session.add(db_hero) 1abc
49 session.commit() 1abc
50 session.refresh(db_hero) 1abc
51 return db_hero 1abc
54@app.get("/heroes/", response_model=list[HeroPublic]) 1abc
55def read_heroes(): 1abc
56 with Session(engine) as session: 1abc
57 heroes = session.exec(select(Hero)).all() 1abc
58 return heroes 1abc