mirror of
https://github.com/fastapi/fastapi.git
synced 2026-04-13 03:20:37 -04:00
✨ Add new tutorial for SQL databases with SQLModel (#12285)
This commit is contained in:
committed by
GitHub
parent
13a18f80b3
commit
7daaac2bc3
74
docs_src/sql_databases/tutorial001_an.py
Normal file
74
docs_src/sql_databases/tutorial001_an.py
Normal file
@@ -0,0 +1,74 @@
|
||||
from typing import List, Union
|
||||
|
||||
from fastapi import Depends, FastAPI, HTTPException, Query
|
||||
from sqlmodel import Field, Session, SQLModel, create_engine, select
|
||||
from typing_extensions import Annotated
|
||||
|
||||
|
||||
class Hero(SQLModel, table=True):
|
||||
id: Union[int, None] = Field(default=None, primary_key=True)
|
||||
name: str = Field(index=True)
|
||||
age: Union[int, None] = Field(default=None, index=True)
|
||||
secret_name: str
|
||||
|
||||
|
||||
sqlite_file_name = "database.db"
|
||||
sqlite_url = f"sqlite:///{sqlite_file_name}"
|
||||
|
||||
connect_args = {"check_same_thread": False}
|
||||
engine = create_engine(sqlite_url, connect_args=connect_args)
|
||||
|
||||
|
||||
def create_db_and_tables():
|
||||
SQLModel.metadata.create_all(engine)
|
||||
|
||||
|
||||
def get_session():
|
||||
with Session(engine) as session:
|
||||
yield session
|
||||
|
||||
|
||||
SessionDep = Annotated[Session, Depends(get_session)]
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
|
||||
@app.on_event("startup")
|
||||
def on_startup():
|
||||
create_db_and_tables()
|
||||
|
||||
|
||||
@app.post("/heroes/")
|
||||
def create_hero(hero: Hero, session: SessionDep) -> Hero:
|
||||
session.add(hero)
|
||||
session.commit()
|
||||
session.refresh(hero)
|
||||
return hero
|
||||
|
||||
|
||||
@app.get("/heroes/")
|
||||
def read_heroes(
|
||||
session: SessionDep,
|
||||
offset: int = 0,
|
||||
limit: Annotated[int, Query(le=100)] = 100,
|
||||
) -> List[Hero]:
|
||||
heroes = session.exec(select(Hero).offset(offset).limit(limit)).all()
|
||||
return heroes
|
||||
|
||||
|
||||
@app.get("/heroes/{hero_id}")
|
||||
def read_hero(hero_id: int, session: SessionDep) -> Hero:
|
||||
hero = session.get(Hero, hero_id)
|
||||
if not hero:
|
||||
raise HTTPException(status_code=404, detail="Hero not found")
|
||||
return hero
|
||||
|
||||
|
||||
@app.delete("/heroes/{hero_id}")
|
||||
def delete_hero(hero_id: int, session: SessionDep):
|
||||
hero = session.get(Hero, hero_id)
|
||||
if not hero:
|
||||
raise HTTPException(status_code=404, detail="Hero not found")
|
||||
session.delete(hero)
|
||||
session.commit()
|
||||
return {"ok": True}
|
||||
Reference in New Issue
Block a user