postman FastAPI BaseModels中的字典以及如何发送正确的json主体

yvfmudvl  于 2022-11-07  发布在  Postman
关注(0)|答案(1)|浏览(229)

我目前正在努力定义一个基础模型,该模型正确地显示我想要使用postman的“raw body”(类型设置为JSON)发送给它的数据。
我想发送一个如下所示的主体:

{
    "a": [
        {
            "text": "text",
            "language": "en",
            "entities": [
                { "d": "g" },
                { "e": "h" },
                { "f": "i" }
            ]
        },
        {
            "text": "another text",
            "language": "en",
            "entities": [
                { "d": "z" }
            ]
        }
    ], 
    "b": [
        {
            "text": "more texts",
            "language": "en",
            "entities": [
                { "d": "r" },
                { "e": "t" },
                { "f": "z" }
            ]
        }
    ],
    "c": ["d", "e", "f"]
}

fastapi中的端点如下所示:

@app.post("/json")
def method(a: AModel, b: BModel, c: CModel):
  # code

基本型号为:

class Input(BaseModel):
    text: str = Field (
        title="A text", example= "text"
    )
    language: str = Field (
        default=None, title="A language string", max_length=2, example="en"
    )
    entities: Dict[str, str] = Field (
        default=None, title="xxx.", 
        example= [{"d": "x"}, {"f": "y"}]
    )

    class Config:
        orm_mode=True

class CModel (BaseModel):
    c: List[str] = Field (
        title="xxx.", example= ["d", "e", "f"]
    )

class BModel (BaseModel):
    b: List[Input] = Field (
        title="yyy."
    )

class AModel (BaseModel):
    a: List[Input] = Field (
        title="zzz."
    )

但是,将数据发送给 Postman 会返回:

{
    "detail": [
        {
            "loc": [
                "body",
                "trainingdata"
            ],
            "msg": "value is not a valid dict",
            "type": "type_error.dict"
        },
        {
            "loc": [
                "body",
                "testingdata"
            ],
            "msg": "value is not a valid dict",
            "type": "type_error.dict"
        },
        {
            "loc": [
                "body",
                "entities"
            ],
            "msg": "value is not a valid dict",
            "type": "type_error.dict"
        }
    ]
}

(我知道AModel和BModel具有相同的结构)
现在,我想问一下我需要如何调整我的BaseModel来表示我在初始身体中显示的结构。我见过有类似问题的人,但不能完全确定我的情况。
有人能帮忙吗?
编辑:我忘了提到我不能将d、e和f硬编码到我的BaseModel中,因为这些只是示例,我永远不能确定这些值有哪些键。

afdcj2ne

afdcj2ne1#

entities应为List[Dict[str, str]],您的路由方法应为

class Combo(AModel, BModel, CModel):
    ...

@app.post("/")
def method(combo: Combo):
    return {
        "combo": combo
    }

相关问题