以前做数据校验的时候,用的更多的是Flask-Wtf 或者是自己手写装饰器,今个发现一个好库,强大又简便。
from jsonschema import validate
schema = {
"type" : "object",
"properties" : {
"price" : {"type" : "number"},
"name" : {"type" : "string"},
"list":{"maxItems":2},
"address":{'regex':'bj'},
},
}
validate({"name" : "Eggs", "price" : 34.99,'list':[1,5],'address':'bj-jiuxianqiao'}, schema)
validate([2, 3, 4], {"maxItems" : 2})
from jsonschema import Draft4Validator
schema = {
"$schema": "http://json-schema.org/schema#"
"type": "object",
"properties": {
"name": {"type": "string"},
"email": {"type": "string"},
}
"required": ["email"],
}
Draft4Validator.check_schema(schema)
可以针对一个数据,做多个判断。
{
"title": "Example Schema",
"type": "object",
"properties": {
"firstName": {
"type": "string"
},
"lastName": {
"type": "string"
},
"age": {
"description": "Age in years",
"type": "integer",
"minimum": 0
}
},
"required": ["firstName", "lastName"]
}
针对list的长短也是可以进行判断,可以设置最大最少,想看更多的demo大家去官网去瞅瞅吧。
"tags": {
"type": "array",
"items": {
"type": "string"
},
"minItems": 1,
"uniqueItems": true
}
当然还有一些现成的format,比如uri,datetime,hostname,ipv4等等。
大家觉得文章对你有些作用!
如果想赏钱,可以用微信扫描下面的二维码,感谢!
另外再次标注博客原地址 xiaorui.cc