从json模式开始创建有效模型
modeller的Python项目详细描述
用法
您可以使用继承来创建模型:
class User(modeller.Model):
id = ''
_schema = {
'type': 'object',
'properties': {
'name': { 'type': 'string' },
'id': { 'type': 'integer' },
'age': { 'type': 'integer' },
},
'required': [
'name',
'surname',
],
# 'additionalProperties': False,
}
# model will be validated after every instance
me = User(id=01, name='Tommy', surname='Der')
# you can also add additional properties
me.state = 'Italy'
me._validate()
print(me._json())
print(me._yaml())
print(me.surname)
模式在types/schema.yaml
$schema:http://json-schema.org/schema#properties:name:type:stringsurname:type:stringage:type:integerrequired:-name-surname-age
在尝试访问模式中定义的属性时,您可以使用自动验证加载模型,使用点轻松访问属性,并且没有异常。
importyamlimportmodelerschema=yaml.load(open('types/schema.yaml').read())Model=modeler.make_model(schema=schema,)Model(name='Tommaso',surname='De Rossi',age=19)
详细信息
如果要更改此行为overwrite_on_init
方法,模型将在实例化后立即验证自身。
如果试图访问json模式.properties
中的属性,而不是对象中的属性,则model将不返回none。
如果您试图访问对象中不存在且json架构中不存在的属性.properties
,则会引发模型。