FastAPI中如何同时使用Depends与Path?
解决方案
方法一:将依赖整合到Path参数中
修改event_id的定义,把依赖函数通过Path的dependency参数传入,这样既能保留Swagger所需的示例、描述和范围限制,又能正常触发依赖:
event_id = Annotated[ int, fastapi.Path( example=123, description="Lore", gt=5, le=100, dependency=fastapi.Depends(dependency_function) ), ]
方法二:显式声明依赖(备用)
如果不想调整Path的定义,也可以在路由函数中额外声明依赖,但这种方式会产生冗余代码,不推荐:
# 保持原event_id定义不变 @router.get('/events/{base_id}') def asd(base_id: common_input_types.event_id, _=Depends(dependency_function)) -> None: do_something()
原因说明
原写法中,当Path参数的Annotated同时包含Depends和Path时,FastAPI会优先处理Path的元数据配置,不会自动触发Depends中的依赖函数。通过将依赖传入Path的dependency参数,FastAPI会在验证Path参数的同时执行依赖函数,实现两者功能的同时生效。
内容的提问来源于stack exchange,提问作者Kulu
相关产品推荐
相关产品推荐

