考慮設計一個用於發送通知的自訂類,其初始化涉及建立與通知伺服器的連接,這是一個耗時的過程。此類別在 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 中的全域NotificationClient初始化導致每次收到請求時都會進行多次冗餘初始化,效率低。
選項 1:利用app.state
FastAPI 允許您使用 app.state 儲存任意狀態。您可以使用生命週期等依賴生命週期函數初始化NotificationClient物件並在FastAPI啟動或關閉期間將其新增至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 的生命週期處理程序可讓您定義可在端點內存取的狀態物件要求.狀態。
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中文網其他相關文章!