Python:使用marshmallow实现Python数据序列化、反序列化、数据验证

marshmallow是一个python数据序列化、反序列化、数据验证的工具库

文档

  • https://marshmallow.readthedocs.io/
  • https://github.com/marshmallow-code/marshmallow

安装

$ pip install -U marshmallow

定义一个Python类

from datetime import datetime


class User:
    def __init__(self, name, email):
        self.name = name
        self.email = email
        self.created_time = datetime.now()

定义一个Schema

from marshmallow import Schema, fields


class UserSchema(Schema):
    name = fields.String()
    email = fields.Email()
    created_time = fields.DateTime()

通过Schema对Python类进行序列化

def main():
    user = User('Tom', '[email protected]')
    schema = UserSchema()

    # 返回dict格式
    res1 = schema.dump(user)
    print(type(res1), res1)
    #  {'created_time': '2023-11-12T18:29:10.178826', 'email': '[email protected]', 'name': 'Tom'}

    # 返回json编码格式的字符串
    res2 = schema.dumps(user)
    print(type(res2), res2)
    #  {"created_time": "2023-11-12T18:29:10.178826", "email": "[email protected]", "name": "Tom"}

if __name__ == '__main__':
    main()

参考文章

  • python之Marshmallow

你可能感兴趣的:(Python,python,开发语言)