python - 如何在 pydantic 模式验证后从蛇案例转变为 Camel 案例

标签 python pydantic

我可以找到一种方法,通过使用别名生成器将基于驼峰类型的请求正文转换为蛇型,但是对于我的回应,我再次想将蛇型转换为驼峰类型发布到架构验证。有什么办法可以实现吗?

示例: 我确实有一个如下的python dict,

{
 "title_name": "search001",
 "status_type": "New" 
}

然后发布到 pydantic 模式验证,我的 dict 应该将蛇案例类型转换为 Camel 案例,如下所示,

{
 "titleName": "search001",
 "statusType": "New" 
}

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

提前致谢。

最佳答案

您可以使用 Alias Generator

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'}

关于python - 如何在 pydantic 模式验证后从蛇案例转变为 Camel 案例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67995510/

相关文章:

python - 编写使用 Python 运行时与 PostgreSQL 数据库通信的 Azure Function App 的最佳实践是什么?

python - FastAPI问题的依赖注入(inject)

python - 如何从 FastAPI 文档中隐藏 Pydantic 鉴别器字段

python - 允许 BaseModel pydantic 的位置参数

python - Google Mirror API 抛出 BadStatusLine 异常(Python)

c++ - 面向 Python 程序员的 C/C++

python - 使用重复的索引 reshape Pandas Dataframe 并填充缺失的行

python - 获取嵌套(连接)表以显示在 FastAPI 和 SQLModel 提供的 OpenAPI 接口(interface)中

python - 如何在 Pydantic 的严格类型(如 StrictStr)中使用验证器?

python - 枕头图像类型错误: an integer is required (got type tuple)