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
« prev ^ index » next coverage.py v7.6.1, created at 2025-05-05 00:03 +0000
1from typing import Annotated, Union 1abcde
3from fastapi import Depends, FastAPI, HTTPException, Query 1abcde
4from sqlmodel import Field, Session, SQLModel, create_engine, select 1abcde
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
14sqlite_file_name = "database.db" 1abcde
15sqlite_url = f"sqlite:///{sqlite_file_name}" 1abcde
17connect_args = {"check_same_thread": False} 1abcde
18engine = create_engine(sqlite_url, connect_args=connect_args) 1abcde
21def create_db_and_tables(): 1abcde
22 SQLModel.metadata.create_all(engine) 1abcde
25def get_session(): 1abcde
26 with Session(engine) as session: 1fghij
27 yield session 1fghij
30SessionDep = Annotated[Session, Depends(get_session)] 1abcde
32app = FastAPI() 1abcde
35@app.on_event("startup") 1abcde
36def on_startup(): 1abcde
37 create_db_and_tables() 1abcde
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
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
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
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