Coverage for docs_src/tutorial/fastapi/update/tutorial001_py310.py: 100%
58 statements
« prev ^ index » next coverage.py v7.7.1, created at 2025-03-24 00:02 +0000
« prev ^ index » next coverage.py v7.7.1, created at 2025-03-24 00:02 +0000
1from fastapi import FastAPI, HTTPException, Query 1abcd
2from sqlmodel import Field, Session, SQLModel, create_engine, select 1abcd
5class HeroBase(SQLModel): 1abcd
6 name: str = Field(index=True) 1abcd
7 secret_name: str 1abcd
8 age: int | None = Field(default=None, index=True) 1abcd
11class Hero(HeroBase, table=True): 1abcd
12 id: int | None = Field(default=None, primary_key=True) 1abcd
15class HeroCreate(HeroBase): 1abcd
16 pass 1abcd
19class HeroPublic(HeroBase): 1abcd
20 id: int 1abcd
23class HeroUpdate(SQLModel): 1abcd
24 name: str | None = None 1abcd
25 secret_name: str | None = None 1abcd
26 age: int | None = None 1abcd
29sqlite_file_name = "database.db" 1abcd
30sqlite_url = f"sqlite:///{sqlite_file_name}" 1abcd
32connect_args = {"check_same_thread": False} 1abcd
33engine = create_engine(sqlite_url, echo=True, connect_args=connect_args) 1abcd
36def create_db_and_tables(): 1abcd
37 SQLModel.metadata.create_all(engine) 1abcd
40app = FastAPI() 1abcd
43@app.on_event("startup") 1abcd
44def on_startup(): 1abcd
45 create_db_and_tables() 1abcd
48@app.post("/heroes/", response_model=HeroPublic) 1abcd
49def create_hero(hero: HeroCreate): 1abcd
50 with Session(engine) as session: 1abcd
51 db_hero = Hero.model_validate(hero) 1abcd
52 session.add(db_hero) 1abcd
53 session.commit() 1abcd
54 session.refresh(db_hero) 1abcd
55 return db_hero 1abcd
58@app.get("/heroes/", response_model=list[HeroPublic]) 1abcd
59def read_heroes(offset: int = 0, limit: int = Query(default=100, le=100)): 1abcd
60 with Session(engine) as session: 1abcd
61 heroes = session.exec(select(Hero).offset(offset).limit(limit)).all() 1abcd
62 return heroes 1abcd
65@app.get("/heroes/{hero_id}", response_model=HeroPublic) 1abcd
66def read_hero(hero_id: int): 1abcd
67 with Session(engine) as session: 1abcd
68 hero = session.get(Hero, hero_id) 1abcd
69 if not hero: 1abcd
70 raise HTTPException(status_code=404, detail="Hero not found") 1abcd
71 return hero 1abcd
74@app.patch("/heroes/{hero_id}", response_model=HeroPublic) 1abcd
75def update_hero(hero_id: int, hero: HeroUpdate): 1abcd
76 with Session(engine) as session: 1abcd
77 db_hero = session.get(Hero, hero_id) 1abcd
78 if not db_hero: 1abcd
79 raise HTTPException(status_code=404, detail="Hero not found") 1abcd
80 hero_data = hero.model_dump(exclude_unset=True) 1abcd
81 db_hero.sqlmodel_update(hero_data) 1abcd
82 session.add(db_hero) 1abcd
83 session.commit() 1abcd
84 session.refresh(db_hero) 1abcd
85 return db_hero 1abcd