如何接收非原始对象作为查询参数?

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

我正在尝试接收一个重要的查询参数对象。目前,我正在通过 json 编码的字符串执行此操作,因为对象似乎被假定在

fastapi
中到达主体,因此我必须在服务器上执行类似的操作:

class MyParam(pydantic.BaseClass):
  param1: list[str]
  param2: typing.Dict[str, SomeOtherPydanticType]

@router.get("/my/route")
def get_vhist_snap_pnl(
    param: pydantic.types.Json = fastapi.Query(
        ...,
        description="json-encoded dictionary",
    )
):
    obj = MyParam(param)

    ...

我可以使用

param
构造
MyParam
的实例,如上所述,但是
fastapi
直接在函数声明中为我执行此操作会很好,因为我会得到更好的 swagger 文档,并且会更少要写的代码。我怎样才能做到这一点?

python fastapi
1个回答
0
投票

您可以从

Query
获取 json 格式的实际字符串,然后
model_validate_json
获取您的
MyParam
对象:

from typing import Annotated

from fastapi import Query
from pydantic import BaseModel


class MyParam(BaseModel):
    param1: list[str]
    param2: dict[str, SomeOtherPydanticType]


async def get_param(
    json_str: Annotated[str, Query(description="json-encoded dictionary")],
) -> MyParam:
    return MyParam.model_validate_json(json_str)


@router.get("/my/route")
def get_vhist_snap_pnl(param: Annotated[MyParam, get_param]):
    print(param.param1)
    print(param.param2)
© www.soinside.com 2019 - 2024. All rights reserved.