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