Coverage for docs_src/tutorial/fastapi/multiple_models/tutorial001_py39.py: 100%
40 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 typing import Optional 1abcd
3from fastapi import FastAPI 1abcd
4from sqlmodel import Field, Session, SQLModel, create_engine, select 1abcd
7class Hero(SQLModel, table=True): 1abcd
8 id: Optional[int] = Field(default=None, primary_key=True) 1abcd
9 name: str = Field(index=True) 1abcd
10 secret_name: str 1abcd
11 age: Optional[int] = Field(default=None, index=True) 1abcd
14class HeroCreate(SQLModel): 1abcd
15 name: str 1abcd
16 secret_name: str 1abcd
17 age: Optional[int] = None 1abcd
20class HeroPublic(SQLModel): 1abcd
21 id: int 1abcd
22 name: str 1abcd
23 secret_name: str 1abcd
24 age: Optional[int] = None 1abcd
27sqlite_file_name = "database.db" 1abcd
28sqlite_url = f"sqlite:///{sqlite_file_name}" 1abcd
30connect_args = {"check_same_thread": False} 1abcd
31engine = create_engine(sqlite_url, echo=True, connect_args=connect_args) 1abcd
34def create_db_and_tables(): 1abcd
35 SQLModel.metadata.create_all(engine) 1abcd
38app = FastAPI() 1abcd
41@app.on_event("startup") 1abcd
42def on_startup(): 1abcd
43 create_db_and_tables() 1abcd
46@app.post("/heroes/", response_model=HeroPublic) 1abcd
47def create_hero(hero: HeroCreate): 1abcd
48 with Session(engine) as session: 1abcd
49 db_hero = Hero.model_validate(hero) 1abcd
50 session.add(db_hero) 1abcd
51 session.commit() 1abcd
52 session.refresh(db_hero) 1abcd
53 return db_hero 1abcd
56@app.get("/heroes/", response_model=list[HeroPublic]) 1abcd
57def read_heroes(): 1abcd
58 with Session(engine) as session: 1abcd
59 heroes = session.exec(select(Hero)).all() 1abcd
60 return heroes 1abcd