datamodel-code-generator によるコード生成¶
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 スキーマ ファイルから 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"
}
}
}
}
}
モデル.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
詳細については、公式ドキュメントをご覧ください。