ホームページ > バックエンド開発 > Python チュートリアル > FastAPI エンドポイント全体でグローバル オブジェクトを効率的に初期化して再利用するにはどうすればよいですか?

FastAPI エンドポイント全体でグローバル オブジェクトを効率的に初期化して再利用するにはどうすればよいですか?

Barbara Streisand
リリース: 2024-11-30 14:54:14
オリジナル
319 人が閲覧しました

How to Efficiently Initialize and Reuse a Global Object Across FastAPI Endpoints?

グローバル オブジェクトまたは変数を初期化し、すべての FastAPI エンドポイントで再利用する方法?

バックグラウンド

通知を送信するために設計されたカスタム クラスを考えてみましょう。その初期化には通知サーバーへの接続の確立が含まれ、これは時間のかかるプロセスです。このクラスは、エンドポイントの応答の遅延を避けるために、FastAPI のバックグラウンド タスク内で利用されます。ただし、現在のアプローチには次のような制限があります。

file1.py:
noticlient = NotificationClient()

@app.post("/{data}")
def send_msg(somemsg: str, background_tasks: BackgroundTasks):
    result = add_some_tasks(data, background_tasks, noticlient)
    return result

file2.py:
def add_some_tasks(data, background_tasks: BackgroundTasks, noticlient):
    background_tasks.add_task(noticlient.send, param1, param2)
    result = some_operation
    return result
ログイン後にコピー

file1.py のグローバル NoticeClient 初期化では、リクエストを受信するたびに複数の冗長な初期化が発生し、非効率的です。

アプローチ

オプション 1: 利用するapp.state

FastAPI では、app.state を使用して任意の状態を保存できます。ライフスパンなどの依存関係ライフサイクル関数を使用して、FastAPI の起動時またはシャットダウン中に、NotificationClient オブジェクトを初期化し、app.state に追加できます。

from fastapi import FastAPI, Request
from contextlib import asynccontextmanager


@asynccontextmanager
async def lifespan(app: FastAPI):
    ''' Run at startup
        Initialise the Client and add it to app.state
    '''
    app.state.n_client = NotificationClient()
    yield
    ''' Run on shutdown
        Close the connection
        Clear variables and release the resources
    '''
    app.state.n_client.close()


app = FastAPI(lifespan=lifespan)


@app.get('/')
async def main(request: Request):
    n_client = request.app.state.n_client
    # ...
ログイン後にコピー

オプション 2: Starlette のライフスパンを使用する

Starlette のライフスパン ハンドラーを使用すると、エンドポイント内でアクセスできる状態オブジェクトを定義できます。 request.state.

from fastapi import FastAPI, Request
from contextlib import asynccontextmanager


@asynccontextmanager
async def lifespan(app: FastAPI):
    ''' Run at startup
        Initialise the Client and add it to request.state
    '''
    n_client = NotificationClient()
    yield {'n_client': n_client}
    ''' Run on shutdown
        Close the connection
        Clear variables and release the resources
    '''
    n_client.close()


app = FastAPI(lifespan=lifespan)


@app.get('/')
async def main(request: Request):
    n_client = request.state.n_client
    # ...
ログイン後にコピー

以上がFastAPI エンドポイント全体でグローバル オブジェクトを効率的に初期化して再利用するにはどうすればよいですか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
著者別の最新記事
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート