Coverage for docs_src/sql_databases/tutorial001_an_py39.py: 100%

46 statements  

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

1from typing import Annotated, Union 1abcde

2 

3from fastapi import Depends, FastAPI, HTTPException, Query 1abcde

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

5 

6 

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

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

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

10 age: Union[int, None] = Field(default=None, index=True) 1abcde

11 secret_name: str 1abcde

12 

13 

14sqlite_file_name = "database.db" 1abcde

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

16 

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

18engine = create_engine(sqlite_url, connect_args=connect_args) 1abcde

19 

20 

21def create_db_and_tables(): 1abcde

22 SQLModel.metadata.create_all(engine) 1abcde

23 

24 

25def get_session(): 1abcde

26 with Session(engine) as session: 1fghij

27 yield session 1fghij

28 

29 

30SessionDep = Annotated[Session, Depends(get_session)] 1abcde

31 

32app = FastAPI() 1abcde

33 

34 

35@app.on_event("startup") 1abcde

36def on_startup(): 1abcde

37 create_db_and_tables() 1abcde

38 

39 

40@app.post("/heroes/") 1abcde

41def create_hero(hero: Hero, session: SessionDep) -> Hero: 1abcde

42 session.add(hero) 1fghij

43 session.commit() 1fghij

44 session.refresh(hero) 1fghij

45 return hero 1fghij

46 

47 

48@app.get("/heroes/") 1abcde

49def read_heroes( 1abcde

50 session: SessionDep, 

51 offset: int = 0, 

52 limit: Annotated[int, Query(le=100)] = 100, 

53) -> list[Hero]: 

54 heroes = session.exec(select(Hero).offset(offset).limit(limit)).all() 1fghij

55 return heroes 1fghij

56 

57 

58@app.get("/heroes/{hero_id}") 1abcde

59def read_hero(hero_id: int, session: SessionDep) -> Hero: 1abcde

60 hero = session.get(Hero, hero_id) 1fghij

61 if not hero: 1fghij

62 raise HTTPException(status_code=404, detail="Hero not found") 1fghij

63 return hero 1fghij

64 

65 

66@app.delete("/heroes/{hero_id}") 1abcde

67def delete_hero(hero_id: int, session: SessionDep): 1abcde

68 hero = session.get(Hero, hero_id) 1fghij

69 if not hero: 1fghij

70 raise HTTPException(status_code=404, detail="Hero not found") 1fghij

71 session.delete(hero) 1fghij

72 session.commit() 1fghij

73 return {"ok": True} 1fghij