将参数传递给依赖函数使其被识别为查询参数

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

看看下面的路由处理程序

@some_router.post("/some-route") 
async def handleRoute(something = Depends(lambda request : do_something(request, "some-argument"))):     
    return JSONResponse(content = {"msg": "Route"}, status_code = 200)

因此依赖函数“do_something”接受请求和字符串值。但是像这样传递它会使其现在被识别为查询参数,即使它不应该被识别。它只是依赖函数所需的一个参数。

enter image description here

“do_something”实现

async def do_something(request: Request, value: str):

    pass

这显然是一个示例代码。如何将请求与字符串值一起传递到“do_something”依赖函数中而不使其被识别为查询参数?

  • 重写了路由处理程序

  • 使用了默认参数,但这不是 FastAPI 依赖注入的工作原理,所以不好

  • 也许 lambda 本身的使用会迫使 FastAPI 将其识别为查询参数?

  • 尝试将“请求”的类型设置为“请求”,但后来遇到语法问题,尝试将其括在括号中,但仍然不起作用。

  • 向 ChatGPT 寻求指导

dependency-injection fastapi
1个回答
0
投票

要将参数传递给依赖函数,你必须做一些杂技。

def get_do_something(value: str):
    async def fixed_do_something(request: Request):
        return await do_something(request, roles)
    return fixed_do_something

请注意,您现在使用的是嵌套函数,而不是直接传递带有附加参数的请求。这个嵌套函数可以处理额外的要求。遵循此约定可以简化开发并使流程更加高效。

@some_router.post("/some-route") 
async def handleRoute(something = Depends(get_do_something('some-value'))):     
    return JSONResponse(content = {"msg": "Route"}, status_code = 200)
© www.soinside.com 2019 - 2024. All rights reserved.