데이터모델 코드 생성기를 사용한 코드 생성¶
datamodel-code-generator 프로젝트는 다음을 포함하여 거의 모든 데이터 소스에서 pydantic 모델을 생성하는 라이브러리 및 명령줄 유틸리티입니다.
- OpenAPI 3(YAML/JSON)
- JSON 스키마
- JSON/YAML/CSV 데이터(JSON 스키마로 변환됨)
- Python 사전(JSON 스키마로 변환됨)
- GraphQL 스키마
데이터 변환 가능한 JSON이 있지만 세련된 모델이 없을 때마다 이 도구를 사용하면 요청에 따라 유형이 안전한 모델 계층을 생성할 수 있습니다.
설치¶
pip install datamodel-code-generator
예¶
이 경우 datamodel-code-generator는 JSON 스키마 파일에서 pydantic 모델을 생성합니다.
datamodel-codegen --input person.json --input-file-type jsonschema --output model.py
사람.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
자세한 내용은 공식 문서 에서 확인할 수 있습니다.
本文总阅读量次