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

30 statements  

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

1from typing import List, Optional 1fabcde

2 

3from fastapi import FastAPI 1fabcde

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

5 

6 

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

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

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

10 secret_name: str 1fabcde

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

12 

13 

14sqlite_file_name = "database.db" 1fabcde

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

16 

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

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

19 

20 

21def create_db_and_tables(): 1fabcde

22 SQLModel.metadata.create_all(engine) 1fabcde

23 

24 

25app = FastAPI() 1fabcde

26 

27 

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

29def on_startup(): 1abcde

30 create_db_and_tables() 1fabcde

31 

32 

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

34def create_hero(hero: Hero): 1fabcde

35 with Session(engine) as session: 1fabcde

36 session.add(hero) 1fabcde

37 session.commit() 1fabcde

38 session.refresh(hero) 1fabcde

39 return hero 1fabcde

40 

41 

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

43def read_heroes(): 1abcde

44 with Session(engine) as session: 1fabcde

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

46 return heroes 1fabcde