グローバル オブジェクトまたは変数を初期化し、すべての 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 サイトの他の関連記事を参照してください。

pythonusesahybridmodelofcompilation andtertation:1)thepythoninterpretercompilessourcodeodeplatform-indopent bytecode.2)thepythonvirtualmachine(pvm)thenexecuteTesthisbytecode、balancingeaseoputhswithporformance。

pythonisbothintersedand compiled.1)it'scompiledtobytecode forportabalityacrossplatforms.2)bytecodeisthenは解釈され、開発を許可します。

loopsareideal whenyouwhenyouknumberofiterationsinadvance、foreleloopsarebetterforsituationsは、loopsaremoreedilaConditionismetを使用します

henthenumber ofiterationsisknown advanceの場合、dopendonacondition.1)forloopsareideal foriterating over for -for -for -saredaverseversives likelistorarrays.2)whileopsaresupasiable forsaresutable forscenarioswheretheloopcontinupcontinuspificcond

pythonisnotpurelyLepted; itusesahybridapproachofbytecodecodecodecodecodecodedruntimerttation.1)pythoncompilessourcodeintobytecode、whodythepythonvirtualmachine(pvm).2)

ToconcatenateListsinpythothesheElements、使用:1)Operatortokeepduplicates、2)asettoremoveduplicates、or3)listcomplunting for controloverduplicates、各メトドハスディフェルフェルフェントパフォーマンスアンドソーダーインプリテーション。

pythonisantertedlanguage、useaseofuseandflexibility-butfactingporformantationationsincriticalapplications.1)解釈されたlikepythonexecuteline-by-lineを解釈します

Useforloopswhenthenumberofiterationsisknowninadvance、andwhiloopswheniterationsdependonacondition.1)forloopsareidealforsecenceslikelistoranges.2)


ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

Video Face Swap
完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

人気の記事

ホットツール

メモ帳++7.3.1
使いやすく無料のコードエディター

SublimeText3 中国語版
中国語版、とても使いやすい

ゼンドスタジオ 13.0.1
強力な PHP 統合開発環境

SublimeText3 Linux 新バージョン
SublimeText3 Linux 最新バージョン

WebStorm Mac版
便利なJavaScript開発ツール
