FastAPI 依赖工厂

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

我想对 API 使用收取一些积分,并提出了以下依赖项

def charge_call(cost: int):
    async def _charge_call(
        wallet=Depends(get_wallet),
    ):
        await wallet.charge(cost)

    return _charge_call


@router.post(
    "/some-call",
    dependencies=[Depends(charge_call(10)]
)

效果很好,但有一个问题。某些端点可以根据传入参数收取不同数量的积分,我尝试创建另一个工厂并像这样使用它,但它从不调用

_charge_call

def charge_test_call(
        call_type: str,
):
    if call_type == "A":
        cost = 1
    else:
        cost = 2
    return charge_call(cost)


@router.post(
    "/test-call",
    dependencies=[Depends(charge_test_call)]
)
async def test_call(
    call_type: str,
):
    if call_type == "A":
        return "A"
    return "B"

是否可以递归地解决 FastAPI 中的依赖关系,或者我必须重新设计充电的工作方式?

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

这是一个使用高级依赖项使用的工作示例:

class WalletChecker:

    async def __call__(self, call_type: str = "A", wallet: Wallet 
 = Depends(get_wallet)):
        if call_type == "A":
            cost = 1
        else:
            cost = 2

        print(f"Cost: {cost}", call_type)
        await wallet.charge(cost)

wallet_checker = WalletChecker()

@router.post(
    "/test-call",
    dependencies=[Depends(wallet_checker)]
)
def test():
    return {"test": "test"}
© www.soinside.com 2019 - 2024. All rights reserved.