在Python FastAPI中,是否可以有条件地向路径操作注入依赖项

问题描述 投票:0回答:1

我对 Python FastAPI 还很陌生,我在 FastAPI 文档、博客和 stackoverflow 中进行了搜索,但找不到这个问题的准确答案 -

是否可以在路径操作中有条件地注入依赖。

例如: 基于环境变量 Enable_Auth=True 或 False,我应该能够启用或禁用路径操作的 Auth 依赖项

非常感谢任何支持。谢谢

python api dependency-injection fastapi
1个回答
0
投票

也许你可以用这样的技巧注入条件依赖:

from typing import Annotated
import os
from fastapi import Depends

async def dep_func_for_Auth(*args, **kwargs)-> type1:
...

async def dep_func_for_withoutAuth(*args, **kwargs)-> type2:
...

useAuth = os.environ.get("Enable_Auth")

dependency = Annotated[type1 if useAuth else type2,
Depends(dep_func_for_Auth if useAuth else dep_func_for_withoutAuth) 
]

然后你可以将此依赖项注入到任何路径操作函数中,如下所示:

@app.get("/anypath")
async def pathOperationSample(dep: dependency):
...
© www.soinside.com 2019 - 2024. All rights reserved.