首页 > 编程语言 > 详细

Python marshmallow 序列化和反序列化

时间:2021-05-16 01:11:02      阅读:19      评论:0      收藏:0      [点我收藏+]

安装 marshmallow

  • pip install marshmallow

基本使用

  • demo.py
"""
# python 序列化
- 序列化:对象转化为字典
- 反序列化: 字典转化为对象
"""

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)    # 反序列化, many=True 表示为批量序列化
"""
反序列化
schema.load(data, many=True)        # dict    			 	->      对象
schema.loads(data, many=True)      # json 字符串   		->        对象
        
序列化
schema.dump(obj, many=True)        #  对象  			->    dict
schema.dumps(obj, many=True)      #  对象  			->   json 字符串

"""

print(users)    # 打印为 元素为对象的列表,用于迭代
print(type(users))  # 列表

  • serialization.py
from marshmallow import fields, post_load, Schema
from models import Student

class StudentSchema(Schema):

    id = fields.Integer()
    name = fields.Str()
    age = fields.Integer()
    height = fields.Float()
    gender = fields.Str()
    cls_id = fields.Integer()
    is_delete = fields.Int()

    @post_load
    def make(self, data, **kwargs):
        return Student(**data)

Python marshmallow 序列化和反序列化

原文:https://www.cnblogs.com/l806760/p/14772925.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!