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

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 までご連絡ください。
Python:編集と解釈に深く掘り下げますPython:編集と解釈に深く掘り下げますMay 12, 2025 am 12:14 AM

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

Pythonは解釈されたものですか、それとも編集された言語であり、なぜそれが重要なのですか?Pythonは解釈されたものですか、それとも編集された言語であり、なぜそれが重要なのですか?May 12, 2025 am 12:09 AM

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

ループ対pythonのループの場合:説明されたキーの違いループ対pythonのループの場合:説明されたキーの違いMay 12, 2025 am 12:08 AM

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

ループのために:実用的なガイドループのために:実用的なガイドMay 12, 2025 am 12:07 AM

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

Python:それは本当に解釈されていますか?神話を暴くPython:それは本当に解釈されていますか?神話を暴くMay 12, 2025 am 12:05 AM

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

同じ要素を持つPython Concatenateリスト同じ要素を持つPython ConcatenateリストMay 11, 2025 am 12:08 AM

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

解釈対編集言語:Pythonの場所解釈対編集言語:Pythonの場所May 11, 2025 am 12:07 AM

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

ループのために:Pythonでそれぞれを使用するのはいつですか?ループのために:Pythonでそれぞれを使用するのはいつですか?May 11, 2025 am 12:05 AM

Useforloopswhenthenumberofiterationsisknowninadvance、andwhiloopswheniterationsdependonacondition.1)forloopsareidealforsecenceslikelistoranges.2)

See all articles

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

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

ホットツール

メモ帳++7.3.1

メモ帳++7.3.1

使いやすく無料のコードエディター

SublimeText3 中国語版

SublimeText3 中国語版

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

ゼンドスタジオ 13.0.1

ゼンドスタジオ 13.0.1

強力な PHP 統合開発環境

SublimeText3 Linux 新バージョン

SublimeText3 Linux 新バージョン

SublimeText3 Linux 最新バージョン

WebStorm Mac版

WebStorm Mac版

便利なJavaScript開発ツール