Coverage for docs_src/tutorial/fastapi/response_model/tutorial001_py39.py: 100%

30 statements  

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

1from typing import Optional 1abcd

2 

3from fastapi import FastAPI 1abcd

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

5 

6 

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

12 

13 

14sqlite_file_name = "database.db" 1abcd

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

16 

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

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

19 

20 

21def create_db_and_tables(): 1abcd

22 SQLModel.metadata.create_all(engine) 1abcd

23 

24 

25app = FastAPI() 1abcd

26 

27 

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

29def on_startup(): 1abcd

30 create_db_and_tables() 1abcd

31 

32 

33@app.post("/heroes/", response_model=Hero) 1abcd

34def create_hero(hero: Hero): 1abcd

35 with Session(engine) as session: 1abcd

36 session.add(hero) 1abcd

37 session.commit() 1abcd

38 session.refresh(hero) 1abcd

39 return hero 1abcd

40 

41 

42@app.get("/heroes/", response_model=list[Hero]) 1abcd

43def read_heroes(): 1abcd

44 with Session(engine) as session: 1abcd

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

46 return heroes 1abcd