Session with FastAPI Dependency
パス関数の中でSessionを張るコードを、Dependsでsessionを渡すコードに書き換える
code:python
def get_session():
with Session(engine) as session:
yield session
@app.post("/heroes/", response_model=HeroPublic)
def create_hero(*, session: Session = Depends(get_session), hero: HeroCreate):
db_hero = Hero.model_validate(hero)
session.add(db_hero)
session.commit()
session.refresh(db_hero)
return db_hero
get_sessionはCRUDすべてのパス関数に渡せる
And you will see how much these dependencies can help the more you work with FastAPI, to handle permissions, authentication, resources like database sessions, etc. 🚀