我想做的是使用cerberus模式定义作为我唯一的数据模板定义套件。我遇到的问题是如何从架构转到数据模板。我不知道如何针对数据模式从零开始构建。
因此,与其拥有数据并对其进行验证,不如说具有架构并以此为基础进行构建。
我尝试了所有示例,并尝试对空数据集进行验证,以查看是否可以使用错误生成器提供迭代器。
# yaml defined earlier and created this dict
In [7]: print(schema_yaml)
{'networks': {'type': 'list', 'schema': {'type': 'dict', 'schema': {'vlan': {'type': 'dict', 'schema': {'id': {'max': 4094, 'type': 'integer', 'min': 1}, 'name': {'type': 'string'}}}, 'ipv4': {'type': 'dict', 'schema': {'prefix_length': {'type': 'integer'}, 'address': {'type': 'ipv4address'}}}}}}}
# Pulled an example that even created custom validator
In [11]: %cpaste
Pasting code; enter '--' alone on the line to stop or use Ctrl-D.
:class NetworkDataJsonValidator(Validator):
"""
A simple JSON data validator with a custom data type for IPv4 addresses
"""
def _validate_type_ipv4address(self, field, value):
"""
checks that the given value is a valid IPv4 address
"""
try:
# try to create an IPv4 address object using the python3 ipaddress module
ipaddress.IPv4Address(value)
except:
self._error(field, "Not a valid IPv4 address")
--
# Created the cerberus validator
In [8]: validator = NetworkDataJsonValidator(schema_yaml)
# and i can validate known data ok, but I can't figure out a way to just give me an iterator that provide a data "template"
In [19]: print(validator.validate("{}"))
..snipped..
DocumentError: '{}' is not a document, must be a dict
In [20]: print(validator.validate({}))
True
因此,在此示例中,我只希望有一种以编程方式对模式进行自省的方法,从而为我提供一种提示用户或针对该模式自动构建的方法