FastAPI依赖注入:如何在main函数初始化类实例并注入至多端点
在FastAPI中注入main函数初始化的类实例
要实现这个需求,核心是利用FastAPI的Depends依赖注入系统,通过闭包函数封装main中初始化的实例,让多个端点可以复用同一个实例。以下是具体实现步骤和代码示例:
1. 定义可配置的业务类
先编写一个需要配置参数初始化的业务类,用于承载具体逻辑:
class BusinessService: def __init__(self, api_key: str, timeout: int): # 接收外部配置参数,实现高可配置性 self.api_key = api_key self.timeout = timeout def execute_task(self): # 示例业务方法 return f"执行任务:使用API密钥 {self.api_key},超时时间 {self.timeout}s"
2. 在main函数中初始化实例并封装依赖
在main函数里读取配置(可来自环境变量、配置文件等),初始化类实例,再通过闭包函数把实例包装成可注入的依赖:
from fastapi import FastAPI, Depends def main(): # 这里可替换为从配置文件/环境变量读取的真实配置 app_config = { "api_key": "prod_123456", "timeout": 20 } # 初始化类实例 service = BusinessService(**app_config) # 定义依赖函数:返回已初始化的实例 def get_business_service(): return service # 创建FastAPI应用 app = FastAPI(title="Configurable Service Demo") # 在端点中注入依赖 @app.get("/run-task") def run_task(service: BusinessService = Depends(get_business_service)): return {"status": "success", "data": service.execute_task()} @app.get("/show-config") def show_config(service: BusinessService = Depends(get_business_service)): return {"api_key": service.api_key, "timeout": service.timeout} return app # 启动应用 app = main()
关键说明
- 闭包的作用:
get_business_service作为闭包,会捕获main函数中初始化的service实例,每次端点调用都会返回同一个实例(单例模式,适合无状态服务)。 - 高可配置性:main是应用入口,在这里读取配置(比如用
pydantic-settings读取.env文件),可灵活切换开发/生产环境配置,无需修改业务类代码。 - 路由拆分场景:如果使用
APIRouter拆分路由,只需把get_business_service函数传递给路由端点的Depends即可,实例会被所有路由共享。
注意事项
如果业务类是有状态的(比如存储请求级数据),需确保实例线程安全;若需每个请求创建新实例,可将初始化逻辑移到依赖函数内部(但这不符合你在main中初始化的需求)。
内容的提问来源于stack exchange,提问作者michael
相关产品推荐
相关产品推荐

