Skip to content

Instantly share code, notes, and snippets.

@toaco
Last active April 4, 2018 07:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save toaco/4241bfef5bb0cfaccdf9fb6c2a9f2eb8 to your computer and use it in GitHub Desktop.
Save toaco/4241bfef5bb0cfaccdf9fb6c2a9f2eb8 to your computer and use it in GitHub Desktop.
rubric设计

功能

  • 对象转换器,提供load_xxx/dump_xxx方法
  • 对象验证器,定义一个模式,判断一个Python对象是否符合该模式. validate
  • 对象生成器,generate
  • 提供其他库的插件:
    • flask/django等Web框架的表单验证插件
    • pymongo 扩展

对象验证

目标在于提供Pythonic的对象验证方式,如:

schema = {
    'a': [],
    'b': [
        {
            'c': int,
            'd': Int(default=3),
            'e': [str]
        }
    ],
    'c': Int(validator=lambda x: 1 < x < 10)
}

rubric.validate(schema, {
    'a': [],
    'b': [
        {
            'c': 1,
            'd': 2,
            'e': ['hello', 'world']
        }
    ],
    'c': 7
}) # pass

支持的验证类型如下:

  • 简单类型:Int,Str,Bool,Float,Decimal,Null
  • 集合类型:字典,列表,元组,集合
  • 自定义类型

简单类型

简单类型的声明直接使用类型名即可,以Int为例:

schema = Int()
schema.validate(1) # pass
schema.validate('1') # raise exception

可以在定义模式时声明验证规则或者使用自定义的验证规则,如

schema1 = Int(max=100,min=0) # 类型预置的规则
schema2 = Int(validator=lambda x:10<x<100)

其他简单类型和Int类似.

集合类型

集合类型的声明和简单类型也很类似,以List为例:

schema = List()
schema.validate([]) # pass
schema.validate([1]) # pass
schema.validate('1') # raise exception

集合类型也可以使用validator参数定义验证规则,或提供一些预置的规则,如:

schema = List(validator=lambda x:len(x)<1)
schema.validate([]) # pass
schema.validate([1]) # raise exception

schema2 = List(len=1) 

集合类型可以嵌套其他类型的声明,如:

schema = List([Int()])

集合类型的schema可以简写,如List([Int()])可以简写为`[Int()]`, 此时需要使用validate函数验证:

schema = [Int()]
validate(schema, [1]) # pass

简写有助于复杂集合的声明:

schema = {
    'a':Int(),
    'b':Str(),
    'c':{
        'c1':Int()
    }
}

自定义类型

自定义类型只需要提供validate方法即可.

class Person:
   def validate(self, value):
       pass
       
schema = {
    'a':Person(),
}

混合类型声明

有时候某个值的类型可能不确定,或者为几个类型中的一个,此时可以使用混合类型,如:

schema = Or(Int(),Str())
schema.validate(1) # pass
schema.validate('1') # pass

项目地址:https://github.com/toaco/rubric

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment