如何在 pydantic 模式验证后从蛇形案例转变为骆驼式案例

sar*_*mar 14 python pydantic

我可以找到一种方法,通过使用别名生成器将基于驼峰类型的请求正文转换为蛇形案例,但对于我的响应,我再次希望将蛇形案例类型转换为驼峰案例类型发布到模式验证。我有什么办法可以实现这个目标吗?

示例:我有一个 python 字典,如下所示,

{
 "title_name": "search001",
 "status_type": "New" 
}
Run Code Online (Sandbox Code Playgroud)

并发布到 pydantic 模式验证我的字典应该将蛇大小写类型转换为驼峰大小写,如下所示,

{
 "titleName": "search001",
 "statusType": "New" 
}
Run Code Online (Sandbox Code Playgroud)

如何定义 pydantic 模式来解决上述问题?

提前致谢。

小智 17

您可以使用别名生成器

from pydantic import BaseModel


def to_snake_case(string: str) -> str:
    return ''.join(['_' + i.lower() if i.isupper() else i for i in string]).lstrip('_')


class MyModel(BaseModel):
    titleName: str
    statusType: str

    class Config:
        alias_generator = to_snake_case


data = {
    "title_name": "search001",
    "status_type": "New"
}
print(MyModel(**data).dict()) # {'titleName': 'search001', 'statusType': 'New'}

Run Code Online (Sandbox Code Playgroud)


小智 11

如果您已将 Pydantic 升级到 v2,则可以使用别名生成器以非常简单的方式实现它:

from pydantic import BaseModel, ConfigDict
from pydantic.alias_generators import to_camel


class BaseSchema(BaseModel):
    model_config = ConfigDict(
        alias_generator=to_camel,
        populate_by_name=True,
        from_attributes=True,
    )

class UserSchema(BaseSchema):
    id: int
    name: str
Run Code Online (Sandbox Code Playgroud)


llp*_*kio 8

您可以在或中使用别名生成器和 kwarg by_alias的组合:.json.dict

from pydantic import BaseModel

def to_camel(string: str) -> str:
    string_split = string.split("_")
    return string_split[0] + "".join(word.capitalize() for word in string_split[1:])

class Foo(BaseModel):
    title_name: str
    status_type: str

    class Config:
        alias_generator = to_camel

f = Foo.parse_raw(
    """
{
 "titleName": "search001",
 "statusType": "New" 
}"""
)
print(f)  # title_name='search001' status_type='New'
print(f.json(by_alias=True))  # {"titleName": "search001", "statusType": "New"}
print(f.json())  # {"title_name": "search001", "status_type": "New"}

Run Code Online (Sandbox Code Playgroud)

此外,您可以添加allow_population_by_field_name=TrueConfig,以便可以使用原始字段名称或别名来解析/初始化模型。

请注意,在 pydantic V2 中,此配置更改为populate_by_name = True docs