Pydantic Model模型架构的别名字段默认情况下是在Swagger而不是原始字段中
我需要从使用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:
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
创建从您的主要模型继承的子模型可能最容易设置别名生成器,然后用户使用该模型进行验证,而第一个模型是生成架构的。
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.