不要在非路由函数(如类的
__init__
方法或普通模块函数)中直接使用Depends()
或request
。
Depends
和request: Request
是 FastAPI 提供的依赖注入机制的一部分,仅适用于FastAPI 路由函数 或由 FastAPI 调用的依赖函数中。在类初始化、模块级代码、启动事件等 FastAPI 注入上下文之外使用,会导致错误或行为异常。
📌 补充解释:
场景 | 是否能使用 Depends() 或 request: Request |
说明 |
---|---|---|
路由函数中 | ✅ 可以 | FastAPI 自动注入 |
依赖函数中 | ✅ 可以 | 由 FastAPI 调用,注入上下文有效 |
类 __init__ 构造函数中 |
❌ 不可以 | FastAPI 不会注入 Depends,对象不会自动创建 |
模块全局作用域 | ❌ 不可以 | 不在请求上下文中,request 不存在 |
startup / shutdown 事件中 |
❌ 不可以使用 request / Depends |
应直接用 app.state 或显式传参 |
✅ 正确示例
python
# 路由函数中
from fastapi import Request, Depends
@app.get("/info")
def get_info(request: Request, config: Config = Depends(get_config)):
return {"url": config.LLM_MODEL_URL}
❌ 错误示例(类中使用 Depends)
python
# 错误:FastAPI 不会自动创建此类,也不会注入 config
class MyService:
def __init__(self, config: Config = Depends(get_config)):
self.config = config
如需在类中使用配置,应该显式传入 config
,例如:
python
class MyService:
def __init__(self, config: Config):
self.config = config