Python:使用marshmallow实现Python数据序列化、反序列化、数据验证
marshmallow是一个python数据序列化、反序列化、数据验证的工具库
文档
- https://marshmallow.readthedocs.io/
- https://github.com/marshmallow-code/marshmallow
安装
$ pip install -U marshmallow
定义一个Python类
from datetime import datetimeclass User:def __init__(self, name, email):self.name = nameself.email = emailself.created_time = datetime.now()
定义一个Schema
from marshmallow import Schema, fieldsclass UserSchema(Schema):name = fields.String()email = fields.Email()created_time = fields.DateTime()
通过Schema对Python类进行序列化
def main():user = User('Tom', '123456@qq.com')schema = UserSchema()# 返回dict格式res1 = schema.dump(user)print(type(res1), res1)# <class 'dict'> {'created_time': '2023-11-12T18:29:10.178826', 'email': '123456@qq.com', 'name': 'Tom'}# 返回json编码格式的字符串res2 = schema.dumps(user)print(type(res2), res2)# <class 'str'> {"created_time": "2023-11-12T18:29:10.178826", "email": "123456@qq.com", "name": "Tom"}if __name__ == '__main__':main()
参考文章
- python之Marshmallow