Coverage for docs_src/tutorial/fastapi/response_model/tutorial001_py310.py: 100%
29 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 fastapi import FastAPI 1abc
2from sqlmodel import Field, Session, SQLModel, create_engine, select 1abc
5class Hero(SQLModel, table=True): 1abc
6 id: int | None = Field(default=None, primary_key=True) 1abc
7 name: str = Field(index=True) 1abc
8 secret_name: str 1abc
9 age: int | None = Field(default=None, index=True) 1abc
12sqlite_file_name = "database.db" 1abc
13sqlite_url = f"sqlite:///{sqlite_file_name}" 1abc
15connect_args = {"check_same_thread": False} 1abc
16engine = create_engine(sqlite_url, echo=True, connect_args=connect_args) 1abc
19def create_db_and_tables(): 1abc
20 SQLModel.metadata.create_all(engine) 1abc
23app = FastAPI() 1abc
26@app.on_event("startup") 1abc
27def on_startup(): 1abc
28 create_db_and_tables() 1abc
31@app.post("/heroes/", response_model=Hero) 1abc
32def create_hero(hero: Hero): 1abc
33 with Session(engine) as session: 1abc
34 session.add(hero) 1abc
35 session.commit() 1abc
36 session.refresh(hero) 1abc
37 return hero 1abc
40@app.get("/heroes/", response_model=list[Hero]) 1abc
41def read_heroes(): 1abc
42 with Session(engine) as session: 1abc
43 heroes = session.exec(select(Hero)).all() 1abc
44 return heroes 1abc