Как проверить объект вложенного словаря в Cerberus

Вот пример данных, которые необходимо проверить. Ключи во вложенном словаре employee_eligibility представляют собой числовую строку "[0-9]+".

{
  "client_id": 1,
  "subdomain": "Acme",
  "shifts": [
    20047, 20048, 20049
  ],
  "employee_eligibility": {
    "1": {
      "20047": 1,
      "20048": 0,
      "20049": 1
    },
    "2": {
      "20047": 1,
      "20048": 0,
      "20049": 1
    },
    "3": {
      "20047": 1,
      "20048": 1,
      "20049": 0
    }
  }
}

Я написал следующую схему для проверки:

    {
        "client_id": {"type": "integer"},
        "subdomain": {"type": "string"},
        "shifts": {"type": "list", "schema": {"type": "integer"}},
        "employee_eligibility": {
            "type": "dict",
            "keysrules": {"type": "string", "regex": "[0-9]+"},
            "schema": {
                "type": "dict",
                "keysrules": {"type": "string", "regex": "[0-9]+"},
                "schema": {"type": "integer"}
            }
        },
    }

Когда я запускаю проверку, я получаю следующую ошибку:

{'employee_eligibility': ['must be of dict type']}

person Adam    schedule 17.01.2020    source источник
comment
вы сделали опечатку. keysules должно быть keysrules   -  person khuynh    schedule 17.01.2020
comment
Спасибо, разъедините клавиатуру и кресло :), исправлена ​​опечатка, теперь выдает ошибку {'employee_eligibility': ['must be of dict type']}   -  person Adam    schedule 17.01.2020
comment
отметьте правильный ответ как принятый.   -  person funky-future    schedule 12.03.2020


Ответы (1)


Ваша схема немного отличается, вам нужно будет использовать valuesrules для проверки значений ваших словарей.

schema = {
    "client_id": {"type": "integer"},
    "subdomain": {"type": "string"},
    "shifts": {"type": "list", "schema": {"type": "integer"}},

    # `employee_eligibility` is a dictionary
    "employee_eligibility": {
        "type": "dict",

        # the keys in `employee_eligibility` are strings matching this regex
        "keysrules": {"type": "string", "regex": "^[0-9]+"},

        # the values in `employee_eligibility` are also dictionaries with keys
        # that are strings that match this regex and integer values
        "valuesrules": {
            "type": "dict",
            "keysrules": {"type": "string", "regex": "^[0-9]+"},
            "valuesrules": {"type": "integer"},
        },
    },
}

изменить: добавлены некоторые комментарии для комментирования примера

person khuynh    schedule 17.01.2020