簡體   English   中英

帶有單個字典或字典列表的 Cerberus 模式

[英]Cerberus schema with single dict or list of dicts

我正在嘗試構建一個模式,其中語句可以是單個字典或字典列表。 前任:

{'Document': {'key': 'value'}}

或多個鍵:

{'Document': [ {'key1': 'value1'}, {'key2': 'value2'}, {'key3': 'value3'}]}

按照我使用此架構測試的文檔:

v.schema = {'Document': {'type': ['dict', 'list'], 'schema': {'type': 'dict'}}}

這是 output:

>>> v.schema = {'Document': {'type': ['dict', 'list'], 'schema': {'type': 'dict'}}}
>>> v.validate({'Document': [{'key1': 'value1'}, {'key2': 'value2'}, {'key3': 'value3'}]})
True
>>> v.validate({'Document': {'key': 'value'} })
False
>>> v.errors
{'Document': ['must be of dict type']}

測試代碼:

import cerberus

if __name__ == '__main__':
    v = cerberus.Validator()
    v.schema = {'Document': {'type': ['dict', 'list'], 'schema': {'type': 'dict'}}}
    print(v.validate({'Document': [{'key1': 'value1'}, {'key2': 'value2'}, {'key3': 'value3'}]}))
    print(v.validate({'Document': {'key': 'value'}}))
    print(v.errors)

第二種情況,該值是 dict 類型,但我收到此錯誤,而不是正確解釋架構。

我認為問題是由於架構規則和映射,如果您刪除架構規則,它應該像這樣工作:

import cerberus

if __name__ == '__main__':
    v = cerberus.Validator()
    v.schema = {'Document': {'type': ['dict', 'list']}}
    print(v.validate({'Document': [{'key1': 'value1'}, {'key2': 'value2'}, {'key3': 'value3'}]}))
    print(v.validate({'Document': {'key': 'value'}}))
    print(v.errors)

有關架構規則和映射的更多信息:

https://docs.python-cerberus.org/en/stable/validation-rules.html#schema-dict

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM