Coverage for docs_src/tutorial/fastapi/multiple_models/tutorial002.py: 100%
36 statements
« prev ^ index » next coverage.py v7.6.1, created at 2024-09-09 00:02 +0000
« prev ^ index » next coverage.py v7.6.1, created at 2024-09-09 00:02 +0000
1from typing import List, Optional 1fabcde
3from fastapi import FastAPI 1fabcde
4from sqlmodel import Field, Session, SQLModel, create_engine, select 1fabcde
7class HeroBase(SQLModel): 1fabcde
8 name: str = Field(index=True) 1fabcde
9 secret_name: str 1fabcde
10 age: Optional[int] = Field(default=None, index=True) 1fabcde
13class Hero(HeroBase, table=True): 1fabcde
14 id: Optional[int] = Field(default=None, primary_key=True) 1fabcde
17class HeroCreate(HeroBase): 1fabcde
18 pass 1fabcde
21class HeroPublic(HeroBase): 1fabcde
22 id: int 1fabcde
25sqlite_file_name = "database.db" 1fabcde
26sqlite_url = f"sqlite:///{sqlite_file_name}" 1fabcde
28connect_args = {"check_same_thread": False} 1fabcde
29engine = create_engine(sqlite_url, echo=True, connect_args=connect_args) 1fabcde
32def create_db_and_tables(): 1fabcde
33 SQLModel.metadata.create_all(engine) 1fabcde
36app = FastAPI() 1fabcde
39@app.on_event("startup") 1fabcde
40def on_startup(): 1abcde
41 create_db_and_tables() 1fabcde
44@app.post("/heroes/", response_model=HeroPublic) 1fabcde
45def create_hero(hero: HeroCreate): 1fabcde
46 with Session(engine) as session: 1fabcde
47 db_hero = Hero.model_validate(hero) 1fabcde
48 session.add(db_hero) 1fabcde
49 session.commit() 1fabcde
50 session.refresh(db_hero) 1fabcde
51 return db_hero 1fabcde
54@app.get("/heroes/", response_model=List[HeroPublic]) 1fabcde
55def read_heroes(): 1abcde
56 with Session(engine) as session: 1fabcde
57 heroes = session.exec(select(Hero)).all() 1fabcde
58 return heroes 1fabcde