Coverage for docs_src/sql_databases/tutorial001_an.py: 100%
47 statements
« prev ^ index » next coverage.py v7.6.1, created at 2025-01-13 13:38 +0000
« prev ^ index » next coverage.py v7.6.1, created at 2025-01-13 13:38 +0000
1from typing import List, Union 1abcde
3from fastapi import Depends, FastAPI, HTTPException, Query 1abcde
4from sqlmodel import Field, Session, SQLModel, create_engine, select 1abcde
5from typing_extensions import Annotated 1abcde
8class Hero(SQLModel, table=True): 1abcde
9 id: Union[int, None] = Field(default=None, primary_key=True) 1abcde
10 name: str = Field(index=True) 1abcde
11 age: Union[int, None] = Field(default=None, index=True) 1abcde
12 secret_name: str 1abcde
15sqlite_file_name = "database.db" 1abcde
16sqlite_url = f"sqlite:///{sqlite_file_name}" 1abcde
18connect_args = {"check_same_thread": False} 1abcde
19engine = create_engine(sqlite_url, connect_args=connect_args) 1abcde
22def create_db_and_tables(): 1abcde
23 SQLModel.metadata.create_all(engine) 1abcde
26def get_session(): 1abcde
27 with Session(engine) as session: 1fghij
28 yield session 1fghij
31SessionDep = Annotated[Session, Depends(get_session)] 1abcde
33app = FastAPI() 1abcde
36@app.on_event("startup") 1abcde
37def on_startup(): 1abcde
38 create_db_and_tables() 1abcde
41@app.post("/heroes/") 1abcde
42def create_hero(hero: Hero, session: SessionDep) -> Hero: 1abcde
43 session.add(hero) 1fghij
44 session.commit() 1fghij
45 session.refresh(hero) 1fghij
46 return hero 1fghij
49@app.get("/heroes/") 1abcde
50def read_heroes( 1abcde
51 session: SessionDep,
52 offset: int = 0,
53 limit: Annotated[int, Query(le=100)] = 100,
54) -> List[Hero]:
55 heroes = session.exec(select(Hero).offset(offset).limit(limit)).all() 1fghij
56 return heroes 1fghij
59@app.get("/heroes/{hero_id}") 1abcde
60def read_hero(hero_id: int, session: SessionDep) -> Hero: 1abcde
61 hero = session.get(Hero, hero_id) 1fghij
62 if not hero: 1fghij
63 raise HTTPException(status_code=404, detail="Hero not found") 1fghij
64 return hero 1fghij
67@app.delete("/heroes/{hero_id}") 1abcde
68def delete_hero(hero_id: int, session: SessionDep): 1abcde
69 hero = session.get(Hero, hero_id) 1fghij
70 if not hero: 1fghij
71 raise HTTPException(status_code=404, detail="Hero not found") 1fghij
72 session.delete(hero) 1fghij
73 session.commit() 1fghij
74 return {"ok": True} 1fghij