跳转至

使用 datamodel-code-generator 生成代码

该数据模型代码生成器项目是一个库和命令行实用程序,用于从几乎任何数据源生成 pydantic 模型,包括:

  • OpenAPI 3 (YAML/JSON)
  • JSON 模式
  • JSON/YAML/CSV 数据(将被转换为 JSON 模式)

  • Python 字典(将转换为 JSON 模式)

  • GraphQL 模式

无论何时,只要你发现自己有任何可转换为 JSON 的数据,但没有 pydantic 模型,这个工具都将允许你按需生成类型安全的模型层次结构。

安装

pip install datamodel-code-generator

示例

在这种情况下,datamodel-code-generator 会根据 JSON Schema 文件创建 pydantic 模型。

datamodel-codegen  --input person.json --input-file-type jsonschema --output model.py

person.json:

{
  "$id": "person.json",
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "Person",
  "type": "object",
  "properties": {
    "first_name": {
      "type": "string",
      "description": "The person's first name."
    },
    "last_name": {
      "type": "string",
      "description": "The person's last name."
    },
    "age": {
      "description": "Age in years.",
      "type": "integer",
      "minimum": 0
    },
    "pets": {
      "type": "array",
      "items": [
        {
          "$ref": "#/definitions/Pet"
        }
      ]
    },
    "comment": {
      "type": "null"
    }
  },
  "required": [
      "first_name",
      "last_name"
  ],
  "definitions": {
    "Pet": {
      "properties": {
        "name": {
          "type": "string"
        },
        "age": {
          "type": "integer"
        }
      }
    }
  }
}

model.py:

# generated by datamodel-codegen:
#   filename:  person.json
#   timestamp: 2020-05-19T15:07:31+00:00
from __future__ import annotations

from typing import Any

from pydantic import BaseModel, Field, conint


class Pet(BaseModel):
    name: str | None = None
    age: int | None = None


class Person(BaseModel):
    first_name: str = Field(..., description="The person's first name.")
    last_name: str = Field(..., description="The person's last name.")
    age: conint(ge=0) | None = Field(None, description='Age in years.')
    pets: list[Pet] | None = None
    comment: Any | None = None

更多信息可以在官方文档中找到


本文总阅读量