补充Depends 和 request: Request 依赖注入用法的注意事项

不要在非路由函数(如类的 __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
相关推荐
软件技术NINI11 分钟前
圣罗兰彩妆html+css 4页
前端·css·html
空空dream32 分钟前
07 | FastAPI + llama.cpp 接入 Langfuse监控Prompt请求
prompt·fastapi·llama
2601_9516152041 分钟前
网站模板 网站网页模板下载
前端·网络·html
酷炫码神1 小时前
Day 1|HTML5:一个商城首页的骨架,从 DOCTYPE 到语义化
前端·html·html5
AI源码2 小时前
鲜花商城(HTML 版)
前端·html
hiahiahia1232 小时前
Message 和对话
服务器·前端·数据库
溪语流沙2 小时前
【Web全栈进阶】Composition API与组件通信:props深入、emit、插槽
前端·css·vue.js
ZoeLandia2 小时前
TypeScript 03:泛型与工具类型
前端·typescript
code_Bo2 小时前
从策划到上线:我和 AI 一起做了个微信记账小程序
前端·ai编程·cursor
Shirley~~3 小时前
Three.js加载Gltf模型并播放动画
前端·3d