Coverage for docs_src/tutorial/fastapi/read_one/tutorial001_py310.py: 100%

42 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2024-09-09 00:02 +0000

1from fastapi import FastAPI, HTTPException 1abc

2from sqlmodel import Field, Session, SQLModel, create_engine, select 1abc

3 

4 

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

9 

10 

11class Hero(HeroBase, table=True): 1abc

12 id: int | None = Field(default=None, primary_key=True) 1abc

13 

14 

15class HeroCreate(HeroBase): 1abc

16 pass 1abc

17 

18 

19class HeroPublic(HeroBase): 1abc

20 id: int 1abc

21 

22 

23sqlite_file_name = "database.db" 1abc

24sqlite_url = f"sqlite:///{sqlite_file_name}" 1abc

25 

26connect_args = {"check_same_thread": False} 1abc

27engine = create_engine(sqlite_url, echo=True, connect_args=connect_args) 1abc

28 

29 

30def create_db_and_tables(): 1abc

31 SQLModel.metadata.create_all(engine) 1abc

32 

33 

34app = FastAPI() 1abc

35 

36 

37@app.on_event("startup") 1abc

38def on_startup(): 1abc

39 create_db_and_tables() 1abc

40 

41 

42@app.post("/heroes/", response_model=HeroPublic) 1abc

43def create_hero(hero: HeroCreate): 1abc

44 with Session(engine) as session: 1abc

45 db_hero = Hero.model_validate(hero) 1abc

46 session.add(db_hero) 1abc

47 session.commit() 1abc

48 session.refresh(db_hero) 1abc

49 return db_hero 1abc

50 

51 

52@app.get("/heroes/", response_model=list[HeroPublic]) 1abc

53def read_heroes(): 1abc

54 with Session(engine) as session: 1abc

55 heroes = session.exec(select(Hero)).all() 1abc

56 return heroes 1abc

57 

58 

59@app.get("/heroes/{hero_id}", response_model=HeroPublic) 1abc

60def read_hero(hero_id: int): 1abc

61 with Session(engine) as session: 1abc

62 hero = session.get(Hero, hero_id) 1abc

63 if not hero: 1abc

64 raise HTTPException(status_code=404, detail="Hero not found") 1abc

65 return hero 1abc