Marshmallow 是一个流行的 Python 库,主要用于对象的序列化和反序列化,它常用于将 Python 对象(如数据类、字典、ORM 模型等)转换为 JSON 格式(序列化),以及将 JSON 数据转换回 Python 对象(反序列化)。
Marshmallow 特别适用于 Web 开发框架(如 Flask、Django、FastAPI),因为它可以轻松地处理请求数据的验证和响应数据的格式化。
核心概念
- Schema(模式):定义数据结构、字段类型、验证规则等。
- 序列化(Serialization):将 Python 对象 → JSON/字典。
- 反序列化(Deserialization):将 JSON/字典 → Python 对象。
- 验证(Validation):在反序列化过程中检查数据是否符合预期。
安装
pip install marshmallow
基本示例
定义 Schema
from marshmallow import Schema, fields, validate
class UserSchema(Schema):
id = fields.Int(dump_only=True) # 只用于输出
name = fields.Str(required=True, validate=validate.Length(min=1, max=50))
email = fields.Email(required=True)
age = fields.Int(validate=validate.Range(min=0, max=120))
is_active = fields.Bool(default=True)
序列化(Python 对象 → JSON)
user = {
"id": 1,
"name": "Alice",
"email": "alice@example.com",
"age": 30,
"is_active": True
}
schema = UserSchema()
result = schema.dump(user)
print(result)
# 输出: {'id': 1, 'name': 'Alice', 'email': 'alice@example.com', 'age': 30, 'is_active': True}
反序列化(JSON → Python 对象)
json_data = {
"name": "Bob",
"email": "bob@example.com",
"age": 25
}
try:
result = schema.load(json_data)
print(result)
# 输出: {'name': 'Bob', 'email': 'bob@example.com', 'age': 25, 'is_active': True}
except Exception as e:
print(e)
验证失败示例
invalid_data = {
"name": "", # 长度不足
"email": "not-an-email", # 无效邮箱
"age": 200 # 超出范围
}
try:
result = schema.load(invalid_data)
except Exception as e:
print(e.messages)
# 输出: {'name': ['Shorter than minimum length 1.'], 'email': ['Not a valid email address.', 'Field may not be null.'], 'age': ['Must be greater than or equal to 0 and less than or equal to 120.']}
常用字段类型
| 字段类型 | 说明 |
|---|---|
fields.Str() |
字符串 |
fields.Int() |
整数 |
fields.Float() |
浮点数 |
fields.Bool() |
布尔值 |
|
| 邮箱地址 |
fields.URL() | URL 地址 |
fields.DateTime() | 日期时间 |
fields.Date() | 日期 |
fields.List() | 列表 |
fields.Dict() | 字典 |
fields.Nested() | 嵌套 Schema |
fields.Method() | 自定义方法序列化 |
fields.Function() | 自定义函数序列化 |
嵌套 Schema
class AddressSchema(Schema): street = fields.Str(required=True) city = fields.Str(required=True)class UserSchema(Schema): name = fields.Str(required=True) address = fields.Nested(AddressSchema())# 使用user_data = { "name": "Charlie", "address": { "street": "123 Main St", "city": "New York" }}schema = UserSchema()result = schema.load(user_data)print(result)# 输出: {'name': 'Charlie', 'address': {'street': '123 Main St', 'city': 'New York'}}与 ORM 集成(以 SQLAlchemy 为例)
from marshmallow_sqlalchemy import SQLAlchemyAutoSchemaclass UserSQLAlchemySchema(SQLAlchemyAutoSchema): class Meta: model = User # 你的 SQLAlchemy 模型 load_instance = True # 反序列化时返回 ORM 实例
常用验证器
from marshmallow import validate
# 字符串长度
name = fields.Str(validate=validate.Length(min=1, max=50))
# 数值范围
age = fields.Int(validate=validate.Range(min=0, max=120))
# 自定义正则表达式
phone = fields.Str(validate=validate.Regexp(r'^d{11}$'))
# 自定义验证函数
def validate_email(value):
if not value.endswith('@example.com'):
raise Exception("Email must be from example.com")
email = fields.Email(validate=validate_email)
最佳实践
- 使用
dump_only和load_only:避免敏感字段(如密码)被序列化或反序列化。 - 使用
required=True:确保必填字段存在。 - 使用验证器:在 Schema 层进行数据验证,而不是在业务逻辑中。
- 使用
Nested字段:处理复杂数据结构。 - 使用
post_load装饰器:在反序列化后执行自定义逻辑。
class UserSchema(Schema):
name = fields.Str(required=True)
email = fields.Email(required=True)
@post_load
def make_user(self, data, kwargs):
return User(data) # 返回自定义对象
Marshmallow 是一个强大且灵活的库,适合处理数据验证和序列化/反序列化任务,它在 Web 开发中非常有用,尤其是与 Flask、Django 或 FastAPI 等框架结合使用时。
如果你有任何具体问题或需要更详细的示例,请告诉我!
首发原创文章,作者:世雄 - 原生数据库架构专家,如若转载,请注明出处:https://idctop.com/article/477555.html



