python marshmallow库
Posted Tarantula
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python marshmallow库相关的知识,希望对你有一定的参考价值。
实现python对象和原生数据相互转换,如实现object -> dict, objects -> list,string -> dict, string -> list等的转换功能,另外它还停工了非常丰富的数据类型转换和校验API。
pip install marshmallow
调用load事件(loads,dump,dumps)
from marshmallow import fields, post_load, Schema data = [{"name": "lin", "age": 23}, {"name": "fang", "age": 20}] class User(object): def __init__(self, name, age): self.name = name self.age = age class UserSchema(Schema): name = fields.Str() age = fields.Integer() @post_load def make(self, data, **kwargs): return User(**data) schema = UserSchema() users = schema.load(data, many=True)
如果是单个数据,只需要把load方法的many参数去掉。
验证功能
示例1:
from marshmallow import ValidationError try: schema = UserSchema() user, error = schema.load(data) print(user, error) except ValidationError as e: print(\'e.message\', e.messages) print(\'e.valid_data\', e.valid_data)
e.message和e.valid_data包括了错误的信息和正确的字段结果,结果如下:
示例2(更多的验证内容):
from pprint import pprint from marshmallow import fields, post_load, Schema, validate, ValidationError class UserSchema(Schema): name = fields.Str(validate=validate.Length(min=3)) permission = fields.Str(validate=validate.OneOf([\'read\', \'write\', \'admin\'])) age = fields.Integer(validate=validate.Range(min=18, max=70)) data = {"name": "fa", "permission": \'user\', "age": 17} try: UserSchema().load(data) except ValidationError as e: pprint(e.messages)
验证的结果如下:
示例3(自定义认证信息):
from pprint import pprint from marshmallow import fields, post_load, Schema, validate, ValidationError def validate_quantity(num): if num < 0: raise ValidationError(\'必须大于0\') if num > 20: raise ValidationError(\'必须小于20\') class ItemSchema(Schema): quantity = fields.Integer(validate=validate_quantity) data = {\'quantity\': 21} try: result = ItemSchema().load(data) except ValidationError as e: pprint(e.messages)
输出结果如下:
更优雅的写法:
from pprint import pprint from marshmallow import fields, post_load, Schema, validates, ValidationError class ItemSchema(Schema): quantity = fields.Integer() @validates(\'quantity\') def validate_quantity(self, num): if num < 0: raise ValidationError(\'必须大于0\') if num > 20: raise ValidationError(\'必须小于20\') data = {\'quantity\': 21} try: result = ItemSchema().load(data) except ValidationError as e: pprint(e.messages)
示例4(必填字段):
from pprint import pprint from marshmallow import fields, post_load, Schema, validates, ValidationError class UserSchema(Schema): name = fields.String(required=True, error_messages={\'required\': \'必填字段\'}) age = fields.Integer(required=True, error_messages={\'required\': \'必填字段\'}) email = fields.Email() try: result = UserSchema().load({\'email\': \'foo@bar.com\'}) except ValidationError as e: pprint(e.messages)
示例5(默认字段):
from marshmallow import Schema, fields import datetime import uuid class UserSchema(Schema): id = fields.UUID(missing=uuid.uuid1) birthdate = fields.DateTime(default=datetime.datetime(2020, 2, 25)) print(UserSchema().load({})) print(UserSchema().dump({}))
结果信息:
更多请参考官方文档:https://marshmallow.readthedocs.io/en/stable
以上是关于python marshmallow库的主要内容,如果未能解决你的问题,请参考以下文章
onRequestPermissionsResult 在片段中不起作用
Android 6.0 (MarshMallow) 上的 HttpURLConnnection 请求失败