通知を送信するために設計されたカスタム クラスを考えてみましょう。その初期化には通知サーバーへの接続の確立が含まれ、これは時間のかかるプロセスです。このクラスは、エンドポイントの応答の遅延を避けるために、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 サイトの他の関連記事を参照してください。