行业知识
Marshmallow,一个有点甜的Python库
前言
在许多场���中,我们常常需要执行Python对象的序列化、反序列化操作。例如,在开发REST API时,或者在进行一些面向对象化的数据加载和保存时,这一功能经常派上用场。
经常cv Python代码的臭宝,接触最多的应该是通过json、pickle模块进行序列化或反序列化,这是一种常见的做法。
import jsondata = {'name': 'John', 'age': 30, 'city': 'New York'}serialized_data = json.dumps(data) 往往Python对象的序列化、反序列化同时也要伴随着数据的处理和校验。
而今天要自我介绍的主角:Marshmallow,则为我们带来更强大的数据序列化和反序列化,更优雅的参数校验、数据处理能力。
Github地址:https://github.com/marshmallow-code/marshmallow
它可以帮助您将复杂的数据类型(例如对象或数据库记录)转换为Python数据类型(例如字典),反之亦然。
它被大量用于Flask和Django等Web开发框架中,以处理数据输入和输出。
楔子
为了执行序列化或反序列化操作,首先需要一个操作对象。在这里,我们先定义一个类:
class Novel: def __init__(self, title, author, genre, pages): self.title = title self.author = author self.genre = genre self.pages = pages# 实例化一个小说对象interesting_novel = Novel(, author="Jane Doe", genre="Fantasy", pages=300)
现在的需求是将这个小说对象转成字典。你会怎么来实现呢?
笨方法
- 手动创建一个字典,将小说对象的属性映射到字典的键和值。
novel_dict = { "title": interesting_novel.title, "author": interesting_novel.author, "genre": interesting_novel.genre, "pages": interesting_novel.pages}- 使用vars函数:
Python 中的 vars 函数可以返回对象的 dict 属性,该属性包含了对象的所有属性和对应的值。这样,你可以直接使用 vars 将对象转换为字典:
novel_dict = vars(interesting_novel)
- 使用__dict__属性:
对于具有__dict__属性的对象,可以直接访问该属性获取对象的属性和值。
novel_dict = interesting_novel.__dict__
- 使用json.loads(json.dumps(obj)):
利用JSON库,通过先将对象转换为JSON字符串,然后再将其解析为字典。
import jsonnovel_json = json.dumps(interesting_novel, default=lambda o: o.__dict__)novel_dict = json.loads(novel_json)
数据类使用dataclass/attrs的内置方法
- dataclass版本
from dataclasses import dataclass, asdictfrom loguru import logger@dataclassclass Novel: title: str author: str genre: str pages: int# 实例化一个小说对象interesting_novel = Novel(, author="Jane Doe", genre="Fantasy", pages=300)# 将对象序列化为字典novel_dict = asdict(interesting_novel)logger.info(novel_dict)# 将字典反序列化为对象new_novel = Novel(**novel_dict)logger.info(new_novel)
- attrs版本
import attrimport cattrfrom loguru import logger@attr.defineclass Novel: title = attr.ib() author = attr.ib() genre = attr.ib() pages = attr.ib()# 实例化一个小说对象interesting_novel = Novel(, author="Jane Doe", genre="Fantasy", pages=300)# 将对象序列化为字典novel_dict = cattr.unstructure(interesting_novel)logger.info(novel_dict)# 将字典反序列化为对象new_novel_dict = {'title': 'AI之旅', 'author': 'HaiGe', 'genre': 'Fantasy', 'pages': 668}new_novel = cattr.structure(new_novel_dict, Novel)logger.info(new_novel)更优雅的方案:marshmallow
上面介绍的几种序列化与反序列化方法看起来已经相当炸裂,但是为什么还要选择 marshmallow 呢?
其实,尽管这些方法能够完成基本的序列化和反序列化任务,但在处理更加复杂的数据结构、数据验证、预处理逻辑以及与其他库的集成等方面,它们可能显得不够灵活和方便。而 marshmallow 库正是为了解决这些问题而诞生的。
marshmallow 提供了强大而灵活的schema(模式)定义,可以精确地控制数据的序列化和反序列化过程。它支持复杂的数据结构、自定义验证器、预处理逻辑等高级功能,同时与许多其他常见的Python库和框架无缝集成。
无论是构建RESTful API、数据持久化、数据迁移或者简单的数据处理、数据验证等领域,marshmallow都能发挥出色的作用,特别适合于需要处理复杂数据结构、进行数据交换的场景。
此外,marshmallow还提供了丰富的文档和社区支持,使得学习和使用起来更加容易。因此,尽管已经有了许多其他方法,但选择marshmallow依然是一个明智的选择,特别是在处理复杂的数据结构和场景下。
marshmallow库的基本用法
安装
要使用marshmallow这个库,需要先安装下:
# 3.20.2pip3 install marshmallow
A. 序列化与反序列化
marshmallow提供了灵活且强大的数据序列化与反序列化功能,可以将复杂的Python数据类型转换为JSON、XML等格式,也能反向将外部数据解析为Python对象。
from marshmallow import Schema, fields, post_loadclass Novel: def __init__(self, title, author, genre, pages): self.title = title self.author = author self.genre = genre self.pages = pages def __repr__(self): return f"Novel(title={self.title!r}, author={self.author!r}, genre={self.genre!r}, pages={self.pages!r})"class NovelSchema(Schema): title = fields.Str() author = fields.Str() genre = fields.Str() pages = fields.Int() @post_load def make(self, data, **kwargs): return Novel(**data)# 创建一个 Novel 对象novel = Novel(, author="Jane Doe", genre="Fantasy", pages=300)# 序列化 Novel 对象novel_schema = NovelSchema()serialized_data = novel_schema.dump(novel)print(serialized_data)# 反序列化deserialized_data = novel_schema.load(serialized_data)print(deserialized_data)这里我们需要稍微区分一下schema的dump方法和dumps方法:dump()方法返回的是dict格式,而dumps()方法返回的是JSON字符串。
同理,load方法用来加载字典,而loads方法用来加载JSON字符串。
让我们再来看下多个对象序列化与反序列化,同样非常简单!!
from marshmallow import Schema, fields, post_loadfrom loguru import loggerclass Novel: def __init__(self, title, author, genre, pages): self.title = title self.author = author self.genre = genre self.pages = pages def __repr__(self): return f"Novel(title={self.title!r}, author={self.author!r}, genre={self.genre!r}, pages={self.pages!r})"class NovelSchema(Schema): title = fields.Str() author = fields.Str() genre = fields.Str() pages = fields.Int() @post_load def make(self, data, **kwargs): return Novel(**data)# 创建一个 Novel 对象novel1 = Novel(, author="暴走的海鸽", genre="Fantasy", pages=300)novel2 = Novel(, author="暴走的海鸽", genre="Fantasy", pages=300)novel3 = Novel(, author="暴走的海鸽", genre="Fantasy", pages=300)novels = [novel1, novel2, novel3]# 序列化 Novel 对象novel_schema = NovelSchema(many=True)serialized_data = novel_schema.dump(novels)logger.info(serialized_data)# 反序列化deserialized_data = novel_schema.load(serialized_data)logger.info(deserialized_data)此外,Schema类具有两个参数用于控制序列化的输出,即only和exclude。only 参数返回的输出结果仅包含列表中指定的类属性,而exclude则正好相反,它会排除列表中指定的类属性。
from marshmallow import Schema, fields, post_load, validates, ValidationError, validatefrom loguru import loggerclass Novel: def __init__(self, title, author, genre="Fantasy2", pages=300): self.title = title self.author = author self.genre = genre self.pages = pages def __repr__(self): return f"Novel(title={self.title!r}, author={self.author!r}, genre={self.genre!r}, pages={self.pages!r})"class NovelSchema(Schema): title = fields.Str(validate=validate.Length(min=1, max=10)) author = fields.Str() genre = fields.Str() pages = fields.Int() @post_load def make(self, data, **kwargs): logger.info(data) return Novel(**data) @validates('pages') def validate_pages(self, value): if value
- attrs版本
- dataclass版本
- 使用json.loads(json.dumps(obj)):
- 使用__dict__属性:
- 使用vars函数:
下一篇:sql怎么删除服务器主体?