fastapi 中的 pydantic 忽略了 schema extra 中的示例

example in schema extra is ignored by pydantic in fastapi

我有一个 pydantic 模型的深层嵌套模式。我想为 fastapi 用户包含一个示例。当我尝试这样做时,pydantic 忽略了该示例。下面是我的模型代码:

# generated by datamodel-codegen:
#   filename:  mllogitem.json
#   timestamp: 2022-02-08T13:47:04+00:00

from __future__ import annotations

from typing import List, Optional

from pydantic import BaseModel


class Input(BaseModel):
    columns: Optional[List[str]] = None
    index: Optional[List[int]] = None
    data: Optional[List[List]] = None


class Output(BaseModel):
    question: Optional[str] = None
    answer: Optional[str] = None
    simScore: Optional[str] = None


class MlFlowData(BaseModel):
    input: Optional[Input] = None
    output: Optional[Output] = None


class MlFlow(BaseModel):
    appId: str
    sessionId: str
    timestamp: str
    type: str
    payload: MlFlowData


class Config:
    arbitrary_types_allowed = True
    schema_extra = {
        "example": {
            "appId": "ConversationalAI",
            "sessionId": "d290f1ee-6c54-4b01-90e6-d701748f0851",
            "timestamp": "2018-09-27T12:40:00Z",
            "type": "Input/output data",
            "payload": {
                "input": {
                    "columns": [
                        "question",
                        "scenario"
                    ],
                    "index": [
                        0
                    ],
                    "data": [
                        [
                            "what is your name?",
                            "gerontology"
                        ]
                    ]
                },
                "output": {
                    "answer": "Henry Williams: My name is Henry Williams.",
                    "question": "What is your name? ",
                    "simScore": "1.0"
                }
            }
        }
    }

我看到 api 中的架构显示为

{
  "appId": "string",
  "sessionId": "string",
  "timestamp": "string",
  "type": "string",
  "payload": {
    "input": {
      "columns": [
        "string"
      ],
      "index": [
        0
      ],
      "data": [
        [
          "string"
        ]
      ]
    },
    "output": {
      "question": "string",
      "answer": "string",
      "simScore": "string"
    }
  }
}

忽略我的例子schema.Any这方面的线索会很有用。

class Config 必须嵌套在您的 class 模型中,在您的示例中 class 位于外部:

class MlFlow(BaseModel):
    appId: str
    sessionId: str
    timestamp: str
    type: str
    payload: MlFlowData

    class Config:
       arbitrary_types_allowed = True
       schema_extra = {}

提示:将您的属性设置为 Optional = None 是多余的。使用其中一个,你不需要两者。