コンテンツにスキップ

高度な依存関係

AIコーディングエージェント

インストール済みのバージョンに対応する公式のFastAPIスキルを使用してください。プロジェクトディレクトリからインストールします:

uvx library-skills

AIを使った開発を参照してください。

🌐 AI と人間による翻訳

この翻訳は、人間のガイドに基づいて AI によって作成されました。🤝

原文の意図を取り違えていたり、不自然な表現になっている可能性があります。🤖

AI LLM をより適切に誘導するのを手伝う ことで、この翻訳を改善できます。

英語版

パラメータ化された依存関係

これまで見てきた依存関係は、固定の関数またはクラスでした。

しかし、多くの異なる関数やクラスを宣言せずに、その依存関係にパラメータを設定したい場合があります。

たとえば、クエリパラメータ q に、ある固定の内容が含まれているかを検査する依存関係が欲しいとします。

ただし、その固定の内容はパラメータ化できるようにしたいです。

「callable」なインスタンス

Python には、クラスのインスタンスを「callable」にする方法があります。

クラス自体(これはすでに callable です)ではなく、そのクラスのインスタンスです。

そのためには、__call__ メソッドを宣言します:

from typing import Annotated

from fastapi import Depends, FastAPI

app = FastAPI()


class FixedContentQueryChecker:
    def __init__(self, fixed_content: str):
        self.fixed_content = fixed_content

    def __call__(self, q: str = ""):
        if q:
            return self.fixed_content in q
        return False


checker = FixedContentQueryChecker("bar")


@app.get("/query-checker/")
async def read_query_check(fixed_content_included: Annotated[bool, Depends(checker)]):
    return {"fixed_content_in_query": fixed_content_included}
🤓 Other versions and variants

Tip

Prefer to use the Annotated version if possible.

from fastapi import Depends, FastAPI

app = FastAPI()


class FixedContentQueryChecker:
    def __init__(self, fixed_content: str):
        self.fixed_content = fixed_content

    def __call__(self, q: str = ""):
        if q:
            return self.fixed_content in q
        return False


checker = FixedContentQueryChecker("bar")


@app.get("/query-checker/")
async def read_query_check(fixed_content_included: bool = Depends(checker)):
    return {"fixed_content_in_query": fixed_content_included}

この場合、この __call__ が、FastAPI が追加のパラメータやサブ依存関係を確認するために使うものになり、後であなたの path operation 関数 のパラメータに値を渡すために呼び出されるものになります。

インスタンスのパラメータ化

そして、__init__ を使って、依存関係を「パラメータ化」するために利用できるインスタンスのパラメータを宣言できます:

from typing import Annotated

from fastapi import Depends, FastAPI

app = FastAPI()


class FixedContentQueryChecker:
    def __init__(self, fixed_content: str):
        self.fixed_content = fixed_content

    def __call__(self, q: str = ""):
        if q:
            return self.fixed_content in q
        return False


checker = FixedContentQueryChecker("bar")


@app.get("/query-checker/")
async def read_query_check(fixed_content_included: Annotated[bool, Depends(checker)]):
    return {"fixed_content_in_query": fixed_content_included}
🤓 Other versions and variants

Tip

Prefer to use the Annotated version if possible.

from fastapi import Depends, FastAPI

app = FastAPI()


class FixedContentQueryChecker:
    def __init__(self, fixed_content: str):
        self.fixed_content = fixed_content

    def __call__(self, q: str = ""):
        if q:
            return self.fixed_content in q
        return False


checker = FixedContentQueryChecker("bar")


@app.get("/query-checker/")
async def read_query_check(fixed_content_included: bool = Depends(checker)):
    return {"fixed_content_in_query": fixed_content_included}

この場合、FastAPI は __init__ に触れたり気にかけたりすることはありません。私たちがコード内で直接使います。

インスタンスの作成

このクラスのインスタンスは次のように作成できます:

from typing import Annotated

from fastapi import Depends, FastAPI

app = FastAPI()


class FixedContentQueryChecker:
    def __init__(self, fixed_content: str):
        self.fixed_content = fixed_content

    def __call__(self, q: str = ""):
        if q:
            return self.fixed_content in q
        return False


checker = FixedContentQueryChecker("bar")


@app.get("/query-checker/")
async def read_query_check(fixed_content_included: Annotated[bool, Depends(checker)]):
    return {"fixed_content_in_query": fixed_content_included}
🤓 Other versions and variants

Tip

Prefer to use the Annotated version if possible.

from fastapi import Depends, FastAPI

app = FastAPI()


class FixedContentQueryChecker:
    def __init__(self, fixed_content: str):
        self.fixed_content = fixed_content

    def __call__(self, q: str = ""):
        if q:
            return self.fixed_content in q
        return False


checker = FixedContentQueryChecker("bar")


@app.get("/query-checker/")
async def read_query_check(fixed_content_included: bool = Depends(checker)):
    return {"fixed_content_in_query": fixed_content_included}

このようにして依存関係を「パラメータ化」できます。いまや "bar" が属性 checker.fixed_content として中に保持されています。

インスタンスを依存関係として使う

その後、Depends(FixedContentQueryChecker) の代わりに Depends(checker) でこの checker を使えます。依存関係はクラスそのものではなく、インスタンスである checker だからです。

依存関係を解決するとき、FastAPI はこの checker を次のように呼び出します:

checker(q="somequery")

...そして、その戻り値を path operation 関数 内の依存関係の値として、パラメータ fixed_content_included に渡します:

from typing import Annotated

from fastapi import Depends, FastAPI

app = FastAPI()


class FixedContentQueryChecker:
    def __init__(self, fixed_content: str):
        self.fixed_content = fixed_content

    def __call__(self, q: str = ""):
        if q:
            return self.fixed_content in q
        return False


checker = FixedContentQueryChecker("bar")


@app.get("/query-checker/")
async def read_query_check(fixed_content_included: Annotated[bool, Depends(checker)]):
    return {"fixed_content_in_query": fixed_content_included}
🤓 Other versions and variants

Tip

Prefer to use the Annotated version if possible.

from fastapi import Depends, FastAPI

app = FastAPI()


class FixedContentQueryChecker:
    def __init__(self, fixed_content: str):
        self.fixed_content = fixed_content

    def __call__(self, q: str = ""):
        if q:
            return self.fixed_content in q
        return False


checker = FixedContentQueryChecker("bar")


@app.get("/query-checker/")
async def read_query_check(fixed_content_included: bool = Depends(checker)):
    return {"fixed_content_in_query": fixed_content_included}

豆知識

ここまでの内容は回りくどく感じられるかもしれません。まだどのように役立つかが明確でないかもしれません。

これらの例は意図的に単純ですが、仕組みを示しています。

セキュリティの章では、同じやり方で実装されたユーティリティ関数があります。

ここまでを理解できていれば、そうしたセキュリティ用ユーティリティが内部でどのように動いているかも理解できています。

依存関係の同時実行数の制限

依存関係を同時に使用できるリクエスト数を制限したい場合があります。

例えば、データベースで利用可能な接続数が限られている場合です。別のリクエストがセッションを使い終わるまで、新しいリクエストをセッション作成前に待機させることができます。

これは Depends() の max_concurrency で実現できます。

SQL データベースのチュートリアルの SessionDep エイリアスを更新してみましょう:

SessionDep = Annotated[Session, Depends(get_session, max_concurrency=5)]

これで、この依存関係を通じて同時にデータベースセッションを開いておけるのは、最大 5 つのリクエストになります。

別のリクエストがセッションを必要とする場合は、それらのセッションのいずれかがクローズされるまで待機します。

待機中はワーカースレッドを占有しないため、それらのスレッドは他のコードを実行できます。

値は正の整数でなければなりません。デフォルトは None で、FastAPI が依存関係の同時実行数を制限しないことを意味します。

ルート間での制限の共有

この例のすべてのルートは同じ SessionDep エイリアスを使うため、セッション数 5 という上限を共有します。

制限を共有するには、この例のような Annotated エイリアスなどで、同じ Depends() オブジェクトを再利用します。

ルートごとに新しい Depends(get_session, max_concurrency=5) を記述すると、それぞれが個別に 5 という上限を持ちます。すべてが同じ get_session 関数を使っていても同様です。

別のアプリケーションで同じ SessionDep を再利用する場合も、両方のアプリケーションが同じイベントループで実行されていれば、制限を共有します。これにはマウントされたアプリケーションも含まれます。

例えば、2 つのアプリケーションが同じデータベースプールに対してこの SessionDep を使う場合、この依存関係を通じて開いておけるセッションは、両方を合わせて最大 5 つです。

アプリケーションが別々のプールを使い、独立した制限を必要とする場合は、アプリケーションごとに別の Depends() オブジェクトを作成してください。

次のセッションを許可する前のクローズ

この例では、get_session は yield を使います。終了コードによるクローズが完了するまで、そのセッションは上限にカウントされます。

依存関係の scope が、その終了コードを実行するタイミングを決定します:

  • デフォルトの scope="request" では、レスポンス送信後に実行されます。
  • scope="function" では、path operation 関数 の終了後、レスポンス送信前に実行されます。

詳しくは早期終了と scopeを参照してください。

yield を使わない依存関係では、関数が終了するまでの間だけ、その呼び出しが上限にカウントされます。

WebSocket ハンドラで yield を使う依存関係を使用する場合、ハンドラが終了し、依存関係の終了コードが完了するまで上限にカウントされます。

備考

キャッシュされた依存関係の値を再利用しても、上限に再度カウントされることはありません。異なる宣言がその値を共有している場合、依存関係を呼び出す宣言だけが、その宣言の上限にカウントされます。

アプリケーションに適した上限の選択

これらのセッションで利用できるデータベース接続数に合った上限を選んでください。

アプリケーションの他の部分もそれらの接続を使う場合は、そのための余裕も残してください。FastAPI はデータベース接続プールのサイズを把握していません。

各ワーカープロセスは独自の上限を持ちます。例えば、この依存関係を使う 2 つのワーカープロセスでは、合わせて最大 10 個のセッションを開いておけます。

技術詳細

制限はイベントループごとにも独立しています。異なるイベントループで実行されるアプリケーションは、同じ Depends() オブジェクトを再利用していても、制限を共有しません。

複数のリソースを必要とする依存関係

FastAPI は、依存関係の制限を適用する前に、そのサブ依存関係を実行します。

そのため、データベースセッションを制限するには、セッションを作成する Depends(get_session, ...) に max_concurrency を設定してください。

リクエストの終了時にしかクローズされないセッションを保持したまま、さらに別のセッションが必要になると、リクエストが進まなくなる可能性があります。

例えば、共有された Depends(get_session, max_concurrency=1, use_cache=False) を同じリクエスト内で 2 回使う場合を考えてみましょう。

最初の呼び出しがセッションを作成します。2 回目の呼び出しは、そのセッションがクローズされるのを待ちます。しかし、最初のセッションはリクエストが終了するまでクローズできず、そのリクエストは 2 回目の呼び出しを待っています。

一方のリクエストがセッションを保持しながら別のリソースを待ち、もう一方がそのリソースを保持しながらセッションを待っている場合にも、2 つのリクエストが進まなくなる可能性があります。

リクエストが複数のリソースを必要とする場合は、同じ順序で取得してください。FastAPI は各制限を個別に適用し、リクエストが必要とするすべてのリソースをあらかじめ確保するわけではありません。

yield、HTTPException、except とバックグラウンドタスクを伴う依存関係

注意

これらの技術的詳細は、ほとんどの場合は不要です。

主に、0.121.0 より前の FastAPI アプリケーションがあり、yield を使う依存関係で問題が発生している場合に有用です。

yield を使う依存関係は、さまざまなユースケースに対応し、いくつかの問題を修正するために時間とともに進化してきました。ここでは変更点の概要を説明します。

yield と scope を伴う依存関係

バージョン 0.121.0 で、yield を使う依存関係に対して Depends(scope="function") がサポートされました。

Depends(scope="function") を使うと、yield の後の終了コードは、クライアントへレスポンスが返される前、path operation 関数 が終了した直後に実行されます。

そして、Depends(scope="request")(デフォルト)を使う場合、yield の後の終了コードはレスポンス送信後に実行されます。

詳しくはドキュメント「yield を使う依存関係 - 早期終了と scope」を参照してください。

yield と StreamingResponse を伴う依存関係、技術詳細

FastAPI 0.118.0 より前では、yield を使う依存関係を使用すると、path operation 関数 が戻ってからレスポンス送信直前に終了コードが実行されていました。

これは、レスポンスがネットワーク上を移動するのを待っている間に、不要にリソースを保持しないようにする意図でした。

この変更により、StreamingResponse を返す場合、yield を持つ依存関係の終了コードはすでに実行されていることになりました。

たとえば、yield を持つ依存関係の中でデータベースセッションを持っていた場合、StreamingResponse はデータをストリーミングしている間にそのセッションを使えません。というのも、yield の後の終了コードでそのセッションがすでにクローズされているからです。

この挙動は 0.118.0 で元に戻され、yield の後の終了コードはレスポンス送信後に実行されるようになりました。

備考

以下で見るように、これはバージョン 0.106.0 より前の挙動ととても似ていますが、いくつかのコーナーケースに対する改良とバグ修正が含まれています。

早期終了コードのユースケース

特定の条件では、レスポンス送信前に yield を持つ依存関係の終了コードを実行する、古い挙動の恩恵を受けられるユースケースがあります。

例えば、yield を持つ依存関係でデータベースセッションを使ってユーザ検証だけを行い、その後は path operation 関数 内ではそのデータベースセッションを一切使わない、かつレスポンス送信に長い時間がかかる(例えばデータをゆっくり送る StreamingResponse)が、何らかの理由でデータベースは使わない、というケースです。

この場合、レスポンスの送信が終わるまでデータベースセッションが保持されますが、使わないのであれば保持する必要はありません。

次のようになります:

import time
from typing import Annotated

from fastapi import Depends, FastAPI, HTTPException
from fastapi.responses import StreamingResponse
from sqlmodel import Field, Session, SQLModel, create_engine

engine = create_engine("postgresql+psycopg://postgres:postgres@localhost/db")


class User(SQLModel, table=True):
    id: int | None = Field(default=None, primary_key=True)
    name: str


app = FastAPI()


def get_session():
    with Session(engine) as session:
        yield session


def get_user(user_id: int, session: Annotated[Session, Depends(get_session)]):
    user = session.get(User, user_id)
    if not user:
        raise HTTPException(status_code=403, detail="Not authorized")


def generate_stream(query: str):
    for ch in query:
        yield ch
        time.sleep(0.1)


@app.get("/generate", dependencies=[Depends(get_user)])
def generate(query: str):
    return StreamingResponse(content=generate_stream(query))

終了コード、すなわち Session の自動クローズは:

# Code above omitted 👆

def get_session():
    with Session(engine) as session:
        yield session

# Code below omitted 👇
👀 Full file preview
import time
from typing import Annotated

from fastapi import Depends, FastAPI, HTTPException
from fastapi.responses import StreamingResponse
from sqlmodel import Field, Session, SQLModel, create_engine

engine = create_engine("postgresql+psycopg://postgres:postgres@localhost/db")


class User(SQLModel, table=True):
    id: int | None = Field(default=None, primary_key=True)
    name: str


app = FastAPI()


def get_session():
    with Session(engine) as session:
        yield session


def get_user(user_id: int, session: Annotated[Session, Depends(get_session)]):
    user = session.get(User, user_id)
    if not user:
        raise HTTPException(status_code=403, detail="Not authorized")


def generate_stream(query: str):
    for ch in query:
        yield ch
        time.sleep(0.1)


@app.get("/generate", dependencies=[Depends(get_user)])
def generate(query: str):
    return StreamingResponse(content=generate_stream(query))

...の部分で定義されており、遅いデータ送信が終わった後に実行されます:

# Code above omitted 👆

def generate_stream(query: str):
    for ch in query:
        yield ch
        time.sleep(0.1)


@app.get("/generate", dependencies=[Depends(get_user)])
def generate(query: str):
    return StreamingResponse(content=generate_stream(query))
👀 Full file preview
import time
from typing import Annotated

from fastapi import Depends, FastAPI, HTTPException
from fastapi.responses import StreamingResponse
from sqlmodel import Field, Session, SQLModel, create_engine

engine = create_engine("postgresql+psycopg://postgres:postgres@localhost/db")


class User(SQLModel, table=True):
    id: int | None = Field(default=None, primary_key=True)
    name: str


app = FastAPI()


def get_session():
    with Session(engine) as session:
        yield session


def get_user(user_id: int, session: Annotated[Session, Depends(get_session)]):
    user = session.get(User, user_id)
    if not user:
        raise HTTPException(status_code=403, detail="Not authorized")


def generate_stream(query: str):
    for ch in query:
        yield ch
        time.sleep(0.1)


@app.get("/generate", dependencies=[Depends(get_user)])
def generate(query: str):
    return StreamingResponse(content=generate_stream(query))

しかし、generate_stream() はデータベースセッションを使わないため、レスポンス送信中にセッションを開いたままにしておく必要は実際にはありません。

SQLModel(または SQLAlchemy)でこの特定のユースケースがある場合は、不要になった時点でセッションを明示的にクローズできます:

# Code above omitted 👆

def get_user(user_id: int, session: Annotated[Session, Depends(get_session)]):
    user = session.get(User, user_id)
    if not user:
        raise HTTPException(status_code=403, detail="Not authorized")
    session.close()

# Code below omitted 👇
👀 Full file preview
import time
from typing import Annotated

from fastapi import Depends, FastAPI, HTTPException
from fastapi.responses import StreamingResponse
from sqlmodel import Field, Session, SQLModel, create_engine

engine = create_engine("postgresql+psycopg://postgres:postgres@localhost/db")


class User(SQLModel, table=True):
    id: int | None = Field(default=None, primary_key=True)
    name: str


app = FastAPI()


def get_session():
    with Session(engine) as session:
        yield session


def get_user(user_id: int, session: Annotated[Session, Depends(get_session)]):
    user = session.get(User, user_id)
    if not user:
        raise HTTPException(status_code=403, detail="Not authorized")
    session.close()


def generate_stream(query: str):
    for ch in query:
        yield ch
        time.sleep(0.1)


@app.get("/generate", dependencies=[Depends(get_user)])
def generate(query: str):
    return StreamingResponse(content=generate_stream(query))

このようにすると、セッションはデータベース接続を解放するため、他のリクエストがそれを使えるようになります。

yield を持つ依存関係で早期終了が必要な別のユースケースがある場合は、あなたの具体的なユースケースと、なぜ yield を持つ依存関係の早期クローズが有益かを説明して、GitHub Discussion の質問を作成してください。

yield を持つ依存関係の早期クローズに納得できるユースケースがある場合は、早期クローズにオプトインする新しい方法を追加することを検討します。

yield と except を伴う依存関係、技術詳細

FastAPI 0.110.0 より前では、yield を持つ依存関係を使い、その依存関係内で except によって例外を捕捉し、再度その例外を送出しなかった場合でも、その例外は自動的に送出(フォワード)され、任意の例外ハンドラまたは内部サーバエラーハンドラに渡されていました。

これは、ハンドラのないフォワードされた例外(内部サーバエラー)による未処理のメモリ消費を修正し、通常の Python コードの挙動と一貫性を持たせるため、バージョン 0.110.0 で変更されました。

バックグラウンドタスクと yield を伴う依存関係、技術詳細

FastAPI 0.106.0 より前では、yield の後で例外を送出することはできませんでした。yield を持つ依存関係の終了コードはレスポンス送信「後」に実行されるため、例外ハンドラはすでに実行済みでした。

これは主に、依存関係が「yield」した同じオブジェクトをバックグラウンドタスク内で利用できるようにするための設計でした。終了コードはバックグラウンドタスク完了後に実行されるからです。

これは、レスポンスがネットワーク上を移動するのを待っている間にリソースを保持しないようにする意図で、FastAPI 0.106.0 で変更されました。

豆知識

加えて、バックグラウンドタスクは通常、独立したロジックの集合であり、(例えば専用のデータベース接続など)それ自身のリソースで個別に扱うべきです。

そのため、このやり方の方がコードはおそらくよりクリーンになります。

この挙動に依存していた場合は、バックグラウンドタスク用のリソースをバックグラウンドタスク内部で作成し、yield を持つ依存関係のリソースに依存しないデータだけを内部で使用するようにしてください。

例えば、同じデータベースセッションを使うのではなく、バックグラウンドタスク内で新しいデータベースセッションを作成し、この新しいセッションでデータベースからオブジェクトを取得します。そして、バックグラウンドタスク関数の引数としてデータベースのオブジェクト自体を渡すのではなく、そのオブジェクトの ID を渡し、バックグラウンドタスク関数内でもう一度そのオブジェクトを取得します。