python读取数据校验数据_python使用schema库进行数据校验

以前做数据校验的时候,用的更多的是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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值