python - Marshmallow:根据数据动态选择Schema?
问题描述
对于 googlers 也是github 中的那个问题。
我有两种类型的用户。我需要通过两种模式之一来验证用户数据。我用我的想法的代码准备了很棒的草稿,当然它不起作用。
class ExtraType0(Schema):
nickname = fields.String()
class ExtraType1(Schema):
id = fields.Integer()
class UserSchema(Schema):
type = fields.String()
extra = fields.Method(deserialize="get_extra_schema_by_user_type")
def get_extra_schema_by_user_type(self, obj):
if obj == 0:
# call ExtraType0 scheme and its (de)serialization
return fields.Nested(ExtraType0())
else:
# call ExtraType01scheme and its (de)serialization
return fields.Nested(ExtraType1())
# correct data
result = UserSchema().load(
{
"type": 0,
"extra": {
"id": 0
}
})
# also correct data
result1 = UserSchema().load(
{
"type": 1,
"extra": {
"nickname": "user123"
}
})
我如何正确选择架构取决于加载的type
字段数据?
解决方案
推荐阅读
- java - 遍历 DataProvider 的 JDBC ResultSet?
- scala - 在 if 保护之前转换 Scala 案例变量
- mysql - 通过结果MySQL的索引获取行的值
- python - 使用 Jinja2 的多个配置文件的 YAML 序列化数据
- css - bulma 的 `pagination-previous` 的源代码在哪里?
- c# - 使用证书解密加密密钥在 .NET 中不起作用但在 Openssql 中起作用
- r - R ggpubr:按组添加平均水平线和配对比较?
- doxygen - Doxygen 功能自动链接问题
- json - Wikipedia API 云:`list` vs `generator` vs `search`
- ios - iOS Graph 上的 Facebook SDK 如何返回视频列表