python使用schema库进行数据校验

以前做数据校验的时候,用的更多的是Flask-Wtf 或者是自己手写装饰器,今个发现一个好库,强大又简便。

from jsonschema import validateschema = {    "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 Draft4Validatorschema = {    "$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等等。

python使用schema库进行数据校验

相关文章:

你感兴趣的文章:

标签云: