読み方のヒント

矢印ボタン(または ← → キー)でページを移動できます。

第4節 要求ごとのSession

4.1 Depends で Session を受け取る

main.py を、データベースから読む形に書き換えます。

from typing import Annotated

from fastapi import Depends, FastAPI, HTTPException
from pydantic import BaseModel
from sqlalchemy import select
from sqlalchemy.orm import Session

from db import get_session
from models import Product

app = FastAPI()

SessionDep = Annotated[Session, Depends(get_session)]


class ProductOut(BaseModel):
    id: str
    name: str
    price: int
    category: str
    reservable: bool


@app.get("/products", response_model=list[ProductOut])
def list_products(session: SessionDep, category: str | None = None, reservable: bool | None = None):
    statement = select(Product).order_by(Product.id)
    if category is not None:
        statement = statement.where(Product.category == category)
    if reservable is not None:
        statement = statement.where(Product.reservable == reservable)
    return session.scalars(statement).all()

Depends(get_session) は、「この関数を呼ぶ前に get_session を呼び、その結果を引数に入れる」という指定です。このように、関数が必要とするものをFastAPIに用意させる仕組みを、依存性の注入と呼びます。

get_session は yield で Session を渡し、応答を返したあとに with の残りを実行して閉じます。要求ごとに新しい Session が作られ、ほかの要求と混ざりません。

Annotated[Session, Depends(get_session)] に SessionDep と名前を付けておくと、ほかの関数でも session: SessionDep と短く書けます。

14 / 20