【问题标题】:marshmallow - choose nested schema based on field value and handle fields 'starting with'marshmallow - 根据字段值选择嵌套模式并处理“以”开头的字段
【发布时间】:2021-10-13 14:45:17
【问题描述】:

我正在解析一个文件并最终得到一个这样的字典:

user_data = {
  "title": "TestA",
  "sects": [
    {
        "type": "cmd",
        "cmd0": {
          "moveX": 12,
          "moveY": 34,
          "action": "fire"
        },
        "session": 9999,
        "cmd1": {
          "moveX": 56,
          "moveY": 78,
          "action": "stop"
        },
        "endType": 0,
      },
      {
        "type": "addUsers",
        "user1": {
          "name": "John",
          "city": "London"
        },
        "user2": {
          "name": "Mary",
          "city": "New York"
        },
        post = "yes"
      }
    ]
}

我正在尝试使用 marshmallow 对其进行验证,但不确定如何处理这两件事:

  1. 对于sects,每个嵌套字典的内容都依赖于type(cmd、addUser 等)。有没有办法根据字段的值来选择架构?
  2. 是否有字段'startsWith'这样的东西来处理我可能有cmd0cmd1...cmdN的事实?

所以,类似于以下内容:

class CmdSchema(schema):
    type = fields.Str()
    cmdN = fields.Dict(...) # Allow cmd1, cmd2, etc
    session = fields.Int()
    endType = fields.Int()

class AddUsersSchema(schema):
    type = fields.Str()
    userN = fields.Dict(...) # Allow user1, user2, etc
    post = fields.Str()

class ParsedFileSchema(schema):
   title = fields.Str()
   sects = fields.Nested(...)   # Choose nested schema based on sects[i]['type']?

注意:我无法更改我正在解析的文件的格式/内容和顺序问题(因此我需要保留 cmd1、cmd2 等的顺序,以便它们能够以正确的顺序进行处理)。

【问题讨论】:

    标签: python marshmallow


    【解决方案1】:

    1/ 你想要实现的是多态性。您可能想查看marshmallow-oneofschema

    2/ 据我所知,这不存在。不过,创建自定义验证器应该不会太难。它甚至可能成为核心。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-17
      相关资源
      最近更新 更多