validictor 官方文档翻译(2018已弃用,学习)

自 2018 年起,此库已弃用,请考虑改用 jsonschema。

概述

validictory 是一个通用的 Python 数据验证器,它允许验证任意 Python 数据结构。
Schema 格式基于JSON Schema 提议,因此与json库结合也可用作 JSON 数据的验证器。
包含来自Ian Lewis 和 Ysuke Muraoka的jsonschema的代码。

示例使用

JSON 文档和模式必须首先加载到 Python 字典类型中,然后才能对其进行验证。

解析一个简单的 JSON 文档:
>>> import validictory
>>> validictory.validate("roast beef", {"type":"string"})
解析更复杂的 JSON 文档:
>>> import json
>>> import validictory

>>> data = json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')
>>> schema = {
...   "type":"array",
...   "items":[
...     {"type":"string"},
...     {"type":"object",
...      "properties":{
...        "bar":{
...          "items":[
...            {"type":"string"},
...            {"type":"any"},
...            {"type":"number"},
...            {"type":"integer"}
...          ]
...        }
...      }
...    }
...   ]
... }
>>> validictory.validate(data,schema)
捕获 ValueErrors 来处理验证问题:
>>> import validictory

>>> try:
...     validictory.validate("short", {"type":"string","minLength":15})
... except ValueError, error:
...     print error
...
Length of value 'short' for field '_data' must be greater than or equal to 15

模式选项

type种类:

验证数据中的项目是否属于特定类型。如果提供了值列表,则将接受任何指定的类型。提供的值可以是以下任意组合:

  • string- str 和 unicode 对象
  • integer- 整数
  • number- 整数和浮点
  • boolean- 布尔值
  • object- 字典
  • array- 列表和元组
  • null- 没有任何
  • any- 任何类型都可以接受
    properties:
properties

对象属性的验证器列表。
本质上,为属性提供的字典中的每个项目
都是应用于数据中具有相同名称的属性(如果存在)的子模式。

# each key in the 'properties' option matches a key in the object that you are validating,
# and the value to each key in the 'properties' option is the schema to validate
# the value of the key in the JSON you are verifying.

data = json.loads(''' {"obj1": {"obj2": 12}}''' )

schema =
{
    "type": "object",
    "properties": {
        "obj1": {
            "type": "object",
            "properties": {
                "obj2": {
                    "type": "integer"
                }
            }
        }
    }
}
validictory.validate(data, schema)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值