官方文档:https://marshmallow.readthedocs.io/en/latest/
Marshmallow,中文译作:棉花糖。是一个轻量级的数据格式转换的模块,也叫序列化和反序列化模块,常用于将复杂的orm模型对象与python原生数据类型之间相互转换。marshmallow提供了丰富的api功能。如下:
Serializing
Deserializing
反序列化器[把可存储或可传输的数据类型转换成数据对象,例如:list/dict->objects/object,string->dict/list]
Validation
数据校验,可以在反序列化阶段,针对要转换数据的内容进行类型验证或自定义验证。
Marshmallow本身是一个单独的库,基于我们当前项目使用框架是flask并且数据库ORM框架使用SQLAlchemy,所以我们可以通过安装flask-sqlalchemy和marshmallow-sqlalchemy集成到项目就可以了。
基本安装和配置
模块安装:
pip install -U marshmallow-sqlalchemy
pip install -U flask-sqlalchemy
pip install -U flask-marshmallow
Marshmallow模块快速使用,我们单独创建一个python文件进行基本的使用,docs/main.py:
from datetime import datetime
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
app = Flask(__name__)
app.config["DEBUG"] = True
app.config["SQLALCHEMY_DATABASE_URI"]="mysql://root:123@127.0.0.1:3306/mofang?charset=utf8mb4"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
db = SQLAlchemy()
db.init_app(app)
ma = Marshmallow()
ma.init_app(app)
class User(db.Model):
__tablename__ = "tb_user"
id = db.Column(db.Integer, primary_key=True, comment="主键ID")
username = db.Column(db.String(255), index=True, comment="用户名")
password = db.Column(db.String(255), comment="登录密码")
mobile = db.Column(db.String(15), index=True, comment="手机号码")
sex = db.Column(db.Boolean, default=True, comment="性别")
email = db.Column(db.String(255), index=True, comment="邮箱")
created_time = db.Column(db.DateTime, default=datetime.now, comment="创建时间")
updated_time = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now, comment="更新时间")
def __repr__(self):
return "<%s: %s>" % (self.__class__.name,self.username)
基本构造器(Schema)
也可以叫基本模式类或基本序列化器类。
marshmallow转换数据格式主要通过构造器类(序列化器)来完成。在marshmallow使用过程中所有的构造器类必须直接或间接继承于Schema基类,而Schema基类提供了数据转换的基本功能:序列化,验证数据和反序列化。
基于Schema完成数据序列化转换
from datetime import datetime
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
app = Flask(__name__)
app.config["DEBUG"] = True
app.config["SQLALCHEMY_DATABASE_URI"]="mysql://root:123@127.0.0.1:3306/yingming?charset=utf8mb4"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
app.config["SQLALCHEMY_ECHO"] = True
db = SQLAlchemy()
db.init_app(app)
ma = Marshmallow()
ma.init_app(app)
"""模型"""
class User(db.Model):
__tablename__ = "desc_user"
id = db.Column(db.Integer, primary_key=True, comment="主键ID")
username = db.Column(db.String(255), index=True, comment="用户名")
password = db.Column(db.String(255), comment="登录密码")
mobile = db.Column(db.String(15), index=True, comment="手机号码")
sex = db.Column(db.Boolean, default=True, comment="性别")
email = db.Column(db.String(255), index=True, comment="邮箱")
created_time = db.Column(db.DateTime, default=datetime.now, comment="创建时间")
updated_time = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now, comment="更新时间")
def __repr__(self):
return "<%s: %s>" % (self.__class__.__name__, self.username)
"""序列化器"""
from marshmallow import Schema, fields
class UserSchema(Schema):
username = fields.String()
mobile = fields.String()
sex = fields.