Pydantic Schema生成指南:自定义JSON Schema
title: Pydantic Schema生成指南:自定义JSON Schema
from pydantic import BaseModel
class User(BaseModel):
id: int
name: str = Field(..., max_length=50)
print(User.schema_json(indent=2))
{
"title": "User",
"type": "object",
"properties": {
"id": {
"title": "Id",
"type": "integer"
},
"name": {
"title": "Name",
"type": "string",
"maxLength": 50
}
},
"required": [
"id",
"name"
]
}
from pydantic import BaseModel, Field
class Product(BaseModel):
sku: str = Field(
...,
json_schema_extra={
"x-frontend": {"widget": "search-input"},
"x-docs": {"example": "ABC-123"}
}
)
print(Product.schema()["properties"]["sku"])
{
"title": "Sku",
"type": "string",
"x-frontend": {
"widget": "search-input"
},
"x-docs": {
"example": "ABC-123"
}
}
from pydantic import BaseModel
from pydantic.json_schema import GenerateJsonSchema
class CustomSchemaGenerator(GenerateJsonSchema):
def generate(self, schema):
if schema["type"] == "string":
schema["format"] = "custom-string"
return schema
class DataModel(BaseModel):
content: str
print(DataModel.schema(schema_generator=CustomSchemaGenerator))
from pydantic import create_model
from pydantic.fields import FieldInfo
def dynamic_model(field_defs: dict):
fields = {}
for name, config in field_defs.items():
fields[name] = (
config["type"],
FieldInfo(**config["field_params"])
)
return create_model('DynamicModel', **fields)
model = dynamic_model({
"timestamp": {
"type": int,
"field_params": {"ge": 0, "json_schema_extra": {"unit": "ms"}}
}
})
from pydantic import BaseModel, ConfigDict
class EnvAwareSchema(BaseModel):
model_config = ConfigDict(json_schema_mode="dynamic")
@classmethod
def __get_pydantic_json_schema__(cls, core_schema, handler):
schema = handler(core_schema)
if os.getenv("ENV") == "prod":
schema["required"].append("audit_info")
return schema
from pydantic import BaseModel
class OpenAPICompatible(BaseModel):
model_config = dict(
json_schema_extra={
"components": {
"schemas": {
"ErrorResponse": {
"type": "object",
"properties": {
"code": {"type": "integer"},
"message": {"type": "string"}
}
}
}
}
}
)
from pydantic import BaseModel, field_validator
class VersionedModel(BaseModel):
model_config = ConfigDict(extra="allow")
@classmethod
def __get_pydantic_json_schema__(cls, core_schema, handler):
schema = handler(core_schema)
schema["x-api-version"] = "2.3"
return schema
class V1Model(VersionedModel):
@classmethod
def __get_pydantic_json_schema__(cls, *args):
schema = super().__get_pydantic_json_schema__(*args)
schema["x-api-version"] = "1.2"
return schema
try:
class InvalidSchemaModel(BaseModel):
data: dict = Field(format="invalid-format")
except ValueError as e:
print(f"Schema配置错误: {e}")
from functools import lru_cache
class CachedSchemaModel(BaseModel):
@classmethod
@lru_cache(maxsize=128)
def schema(cls, **kwargs):
return super().schema(**kwargs)
错误信息 | 原因分析 | 解决方案 |
---|---|---|
ValueError: 无效的format类型 | 不支持的Schema格式 | 检查字段类型与格式的兼容性 |
KeyError: 缺失必需字段 | 动态Schema未正确注入 | 验证__get_pydantic_json_schema__实现 |
SchemaGenerationError | 自定义生成器逻辑错误 | 检查类型映射逻辑 |
MemoryError | 大规模模型未缓存 | 启用模型Schema缓存 |
评论
发表评论