阿小信大人的头像
Life is short (You need Python) Bruce Eckel

colander简单用法2014-09-03 02:58

文档 http://docs.pylonsproject.org/projects/colander/en/latest/#

#-*- coding:utf-8 -*-
__author__ = 'ashin'

from colander import SchemaNode, MappingSchema
from colander import Length, OneOf
from colander import String

class Person(MappingSchema):
    name = SchemaNode(String(), validator = Length(max=5))
    sex = SchemaNode(String(), validator = OneOf(['M', 'F']), missing='M')


person_struct = {
        'name':'ashin',
       # 'sex':'X',
        }

person_schema = Person()

person_deserialized = person_schema.deserialize(person_struct)  #dict type

assert person_deserialized['name'] == 'ashin'
assert person_deserialized['sex'] == 'M'

验证person_struct中的name最大长度为5,sex为M或F中的一个,默认为M

当name的长度大于5时,sex为X时:

raise error
colander.Invalid: {'name': u'Longer than maximum length 5', 'sex': u'"X" is not one of M, F'}

如果您觉得从我的分享中得到了帮助,并且希望我的博客持续发展下去,请点击支付宝捐赠,谢谢!

若非特别声明,文章均为阿小信的个人笔记,转载请注明出处。文章如有侵权内容,请联系我,我会及时删除。

#Python#  
分享到:
阅读[1803] 评论[0]

你可能也感兴趣的文章推荐

本文最近访客

网友185.*.*.9[火星]2020-09-22 22:41
网友116.*.*.41[火星]2020-09-22 22:33
网友185.*.*.5[火星]2020-09-22 22:28
网友216.*.*.226[Seattle]2020-09-22 22:14

发表评论