Pydantic Model模型架构的别名字段默认情况下是在Swagger而不是原始字段中

发布于 2025-01-26 03:01:28 字数 1225 浏览 0 评论 0原文

我需要从使用pascalcase的外部平台(cognito)接收数据,而pydantic模型通过现场别名来支持此数据,在设置中添加alias_generator = to_camel我在设置中我使所有字段都使所有字段都有Pascalcase别名salias selo

通过这种方式,模型:

class AuthenticationResult(BaseModel):
    access_token: str
    expires_in: int
    token_type: str
    refresh_token: str
    id_token: str
    
    class Config:
        alias_generator = to_camel
        allow_population_by_field_name = True

它可以接收以下字典而没有丝毫问题:

data = {
  "AccessToken": "myToken",
  "ExpiresIn": 0,
  "TokenType": "string",
  "RefreshToken": "string",
  "IdToken": "string"
}
auth_data = AuthenticationResult(**data)

print(auth_data.access_token)
# Output: myToken

但是,在应用程序的Swagger文档中,它也以pascalcase格式中,但必须返回snake_case 格式,这很奇怪,因为by_alias默认情况下是错误的。 这是格式:

我需要它以snake_case格式发送给客户端。我该怎么做,以便它继续接受使用pascalcase字典构建

I need to receive data from an external platform (cognito) that uses PascalCase, and the Pydantic model supports this through field aliases, adding an alias_generator = to_camel in the settings I make all fields have a PascalCase alias corresponding

In this way, the model:

class AuthenticationResult(BaseModel):
    access_token: str
    expires_in: int
    token_type: str
    refresh_token: str
    id_token: str
    
    class Config:
        alias_generator = to_camel
        allow_population_by_field_name = True

it can receive the following dictionary without the slightest problem:

data = {
  "AccessToken": "myToken",
  "ExpiresIn": 0,
  "TokenType": "string",
  "RefreshToken": "string",
  "IdToken": "string"
}
auth_data = AuthenticationResult(**data)

print(auth_data.access_token)
# Output: myToken

However, in the application's Swagger documentation it is also in PascalCase format, but it must return in snake_case format, which is strange, since by_alias is False by default.
Here's the format:

Swagger Printscreen

I need it to be in snake_case format to send it to the client. How can I do this, so that it continues to accept being built using a PascalCase dictionary

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

ゃ懵逼小萝莉 2025-02-02 03:01:28

创建从您的主要模型继承的子模型可能最容易设置别名生成器,然后用户使用该模型进行验证,而第一个模型是生成架构的。

Might be easiest to create a sub model inheriting from your main model to set the alias generator on, then user that model for validation and the first one to generate the schema.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文