编程语言
首页 > 编程语言> > Python(二)Marshmallow 库相关学习

Python(二)Marshmallow 库相关学习

作者:互联网

0. 前言

1. Schema

class ImageTpl(Schema):
    value = fields.Dict(required=True, error_messages=get_field_valid_msg("图片模版值"))
    height = fields.Int(required=True, error_messages=get_field_valid_msg("图片模版高度"))
    width = fields.Int(required=True, error_messages=get_field_valid_msg("图片模版宽度"))

2. 序列化

from marshmallow import pprint

user = User(name="Monty", email="monty@python.org")
schema = UserSchema()
result = schema.dump(user)
pprint(result.data)
# {"name": "Monty",
#  "email": "monty@python.org",
#  "created_at": "2014-08-17T14:54:16.049594+00:00"}
from pprint import pprint

user_data = {
    'created_at': '2014-08-11T05:26:03.869245',
    'email': u'ken@yahoo.com',
    'name': u'Ken'
}
schema = UserSchema()
result = schema.load(user_data)
pprint(result.data)
# {'name': 'Ken',
#  'email': 'ken@yahoo.com',
#  'created_at': datetime.datetime(2014, 8, 11, 5, 26, 3, 869245)},

3. 反序列化

from marshmallow import Schema, fields, post_load

class UserSchema(Schema):
    name = fields.Str()
    email = fields.Email()
    created_at = fields.DateTime()

    @post_load
    def make_user(self, data):
        return User(**data)

user_data = {
    'name': 'Ronnie',
    'email': 'ronnie@stones.com'
}
schema = UserSchema()
result = schema.load(user_data)
result.data  # => <User(name='Ronnie')>

4. Field 对象

from marshmallow import Schema, fields, ValidationError

def validate_quantity(n):
    if n < 0:
        raise ValidationError('Quantity must be greater than 0.')
    if n > 30:
        raise ValidationError('Quantity must not be greater than 30.')

class ItemSchema(Schema):
    quantity = fields.Integer(validate=validate_quantity)

in_data = {'quantity': 31}
result, errors = ItemSchema().load(in_data)
errors  # => {'quantity': ['Quantity must not be greater than 30.']}
def get_field_valid_msg(field_name):
    return {
        'required': '[%s] 字段必填' % field_name,
        'type': '[%s] 字段类型不合法' % field_name, # used by Unmarshaller
        'null': '[%s] 字段不能为空' % field_name,
        'validator_failed': '[%s] 字段值不合法' % field_name
    }
......
'components': fields.Nested(Component, required=True, many=True,
                                    error_messages=get_field_valid_msg("组件信息")),
......

5. 验证

@validates_schema
    def validate_element_type(self, value):

        switch = {
            DpaVideoPackageElementType.TEXT : lambda x : x in DpaVideoPackageDataType.text_types(),
            DpaVideoPackageElementType.IMAGE : lambda x : x in DpaVideoPackageDataType.image_types(),
            DpaVideoPackageElementType.LOGO : lambda x : x in DpaVideoPackageDataType.logo_types()
        }

        try:
            if not switch[value['element_type']](value['data_type']):
                raise ValidationError("组件类型和组件数据类型不匹配")
        except KeyError as e:
            raise ValidationError("组件类型不存在")
class ImageOrImageMeta(Schema):
    value = fields.String(required=True, error_messages=get_field_valid_msg("图片或图片元数据值"))
    height = fields.Int(required=True, error_messages=get_field_valid_msg("图片或图片元数据高度"))
    width = fields.Int(required=True, error_messages=get_field_valid_msg("图片或图片元数据宽度"))

class ImageTpl(Schema):
    value = fields.Dict(required=True, error_messages=get_field_valid_msg("图片模版值"))
    height = fields.Int(required=True, error_messages=get_field_valid_msg("图片模版高度"))
    width = fields.Int(required=True, error_messages=get_field_valid_msg("图片模版宽度"))

class TextOrTextMeta(Schema):
    value = fields.String(required=True, error_messages=get_field_valid_msg("文本或文本元数据值"))
    default_val = fields.String(error_messages=get_field_valid_msg("文本或文本元数据默认值"))
    max_length = fields.Int(required=True, error_messages=get_field_valid_msg("文本或文本元数据最大值"))
......
        switch = {
            DpaVideoPackageDataType.IMAGE : lambda x : ImageOrImageMeta().load(x),
            DpaVideoPackageDataType.IMAGE_META : lambda x : ImageOrImageMeta().load(x),
            DpaVideoPackageDataType.IMAGE_TPL : lambda  x : ImageTpl().load(x),
            DpaVideoPackageDataType.TEXT : lambda  x : TextOrTextMeta().load(x),
            DpaVideoPackageDataType.TEXT_META : lambda  x : TextOrTextMeta().load(x),
        }

        result = switch[value['data_type']](value['data'])
        if result.errors:
            raise ValidationError(result.errors)

4. 参考文献

 

标签:Marshmallow,get,Python,fields,messages,学习,field,msg,Schema
来源: https://www.cnblogs.com/wangao1236/p/10899606.html