首页 >后端开发 >Python教程 >如何跨 FastAPI 端点有效地初始化和重用全局对象?

如何跨 FastAPI 端点有效地初始化和重用全局对象?

Barbara Streisand
Barbara Streisand原创
2024-11-30 14:54:14236浏览

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 中的全局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中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn