marshmallow是一个python数据序列化、反序列化、数据验证的工具库
文档
安装
$ 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', '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()