【问题标题】:How to include $id fields in Pydantic.schema()如何在 Pydantic.schema() 中包含 $id 字段
【发布时间】:2021-12-27 00:14:15
【问题描述】:

根据json-schema.org,最好在对象中包含$id 字段。

例如,我正在努力解决如何在顶层实现这一目标;

class MySchema(BaseModel):

    id: str = Field(default="http://my_url/my_schema.json", alias="$id")


if __name__ == '__main__':
    pprint(MySchema.schema())

产量

{'properties': {'$id': {'default': 'http://my_url/my_schema.json',
                        'title': '$Id',
                        'type': 'string'}},
 'title': 'MySchema',
 'type': 'object'}

如何在顶层获取 $id,带有标题和类型,而不是作为嵌套属性?

【问题讨论】:

    标签: python jsonschema pydantic


    【解决方案1】:

    Pydantic provides 多种模式自定义方式。例如,使用schema_extra 配置选项:

    from pydantic import BaseModel
    
    
    class Person(BaseModel):
        name: str
        age: int
    
        class Config:
            schema_extra = {
                '$id': "my.custom.schema"
            }
    
    
    print(Person.schema_json(indent=2))
    

    输出:

    {
      "title": "Person",
      "type": "object",
      "properties": {
        "name": {
          "title": "Name",
          "type": "string"
        },
        "age": {
          "title": "Age",
          "type": "integer"
        }
      },
      "required": [
        "name",
        "age"
      ],
      "$id": "my.custom.schema"
    }
    

    【讨论】:

      猜你喜欢
      • 2017-10-13
      • 2019-01-07
      • 2020-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多