Coverage for docs_src/tutorial/fastapi/simple_hero_api/tutorial001.py: 100%

30 statements  

« prev     ^ index     » next       coverage.py v7.11.0, created at 2025-10-27 00:03 +0000

1from typing import Optional 1abcdefghij

2 

3from fastapi import FastAPI 1abcdefghij

4from sqlmodel import Field, Session, SQLModel, create_engine, select 1abcdefghij

5 

6 

7class Hero(SQLModel, table=True): 1abcdefghij

8 id: Optional[int] = Field(default=None, primary_key=True) 1abcdefghij

9 name: str = Field(index=True) 1abcdefghij

10 secret_name: str 1abcdefghij

11 age: Optional[int] = Field(default=None, index=True) 1abcdefghij

12 

13 

14sqlite_file_name = "database.db" 1abcdefghij

15sqlite_url = f"sqlite:///{sqlite_file_name}" 1abcdefghij

16 

17connect_args = {"check_same_thread": False} 1abcdefghij

18engine = create_engine(sqlite_url, echo=True, connect_args=connect_args) 1abcdefghij

19 

20 

21def create_db_and_tables(): 1abcdefghij

22 SQLModel.metadata.create_all(engine) 1abcdefghij

23 

24 

25app = FastAPI() 1abcdefghij

26 

27 

28@app.on_event("startup") 1abcdefghij

29def on_startup(): 1abcdefghij

30 create_db_and_tables() 1abcdefghij

31 

32 

33@app.post("/heroes/") 1abcdefghij

34def create_hero(hero: Hero): 1abcdefghij

35 with Session(engine) as session: 1abcdefghij

36 session.add(hero) 1abcdefghij

37 session.commit() 1abcdefghij

38 session.refresh(hero) 1abcdefghij

39 return hero 1abcdefghij

40 

41 

42@app.get("/heroes/") 1abcdefghij

43def read_heroes(): 1abcdefghij

44 with Session(engine) as session: 1abcdefghij

45 heroes = session.exec(select(Hero)).all() 1abcdefghij

46 return heroes 1abcdefghij