前言

Flask-RESTful 提供了一种简单的方法来控制您在响应中实际呈现的数据。使用该fields模块,您可以在资源中使用所需的任何对象(ORM 模型/自定义类/等)。
fields还允许您格式化和过滤响应,因此您不必担心暴露内部数据结构。

基本用法

user 表的字段设计如下

class Users(db.Model):
__tablename__ = 'user' # 数据库表名
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
username = db.Column(db.String(50), unique=True, nullable=False)
password = db.Column(db.String(128), nullable=False)
is_active = db.Column(db.Boolean, default=1)
email = db.Column(db.String(64), nullable=True)

def hash_password(self, password):
"""密码加密"""
self.password = sha256_crypt.encrypt(password)

def verify_password(self, password):
"""校验密码"""
return sha256_crypt.verify(password, self.password)

def __repr__(self):
return f"<Users(id='{self.id}', username='{self.username}'...)>"

写一个视图返回用户个人信息,包含id,name,is_active 字段

没用到序列化之前,我们一般是这样写的,先查询到对象,在返回内容的时候,从对象取值


class UserInfo(Resource):

def get(self):
user = Users.query.get(1)
print(f'查询到的数据:{user}')
return {
"msg": 'success',
"data": {
"id": user.id,
"username": user.username,
"is_active": user.is_active
}
}


api.add_resource(UserInfo, '/api/v1/userinfo')

接下来使用Flask-RESTful 提供的 fields 模块序列化输出需要的字段

from flask_restful import Resource, fields, marshal_with

user_fields = {
'id': fields.Integer,
'username': fields.String,
'is_active': fields.Boolean
}


class UserInfo(Resource):

@marshal_with(user_fields)
def get(self):
user = Users.query.get(1)
print(f'查询到的数据:{user}')
return user

访问接口可以看到user对象被序列化成

{
"id": 1,
"username": "test",
"is_active": true
}

装饰器marshal_with实际上是获取您的数据对象并应用字段过滤。编组可以处理单个对象、字典或对象列表。

笔记
marshal_with是一个便利装饰器,在功能上等同于

from flask_restful import Resource, fields, marshal_with, marshal

class UserInfo(Resource):


def get(self):
user = Users.query.get(1)
print(f'查询到的数据:{user}')
return marshal(user, user_fields), 200

marshal_with 装饰器

marshal_with 装饰器的作用对方法的返回值应用编组的装饰器。

使用示例

>>> from flask_restful import fields, marshal_with
>>> mfields = { 'a': fields.Raw }
>>> @marshal_with(mfields)
... def get():
... return { 'a': 100, 'b': 'foo' }
...
...
>>> get()
OrderedDict([('a', 100)])

可选的 envelope 关键字参数用来包装结果输出

>>> @marshal_with(mfields, envelope='data')
... def get():
... return { 'a': 100, 'b': 'foo' }
...
...
>>> get()
OrderedDict([('data', OrderedDict([('a', 100)]))])

envelope 关键字参数使用示例

class UserInfo(Resource):

@marshal_with(user_fields, envelope='data')
def get(self):
user = Users.query.get(1)
print(f'查询到的数据:{user}')
return user

此时接口输出的json 数据如下

{
"data": {
"id": 1,
"username": "test",
"is_active": true
}
}

自定义接口内容输出

一般json 格式的接口我们喜欢返回一个固定格式

{
"code": 0,
"msg": "success",
"data": {

}
}

marshal_with 装饰器只能对return的对象序列化,这里可以使用 marshal() 函数实现部分序列化

from flask_restful import Resource, fields, marshal_with, marshal

user_fields = {
'id': fields.Integer,
'username': fields.String,
'is_active': fields.Boolean
}


class UserInfo(Resource):

def get(self):
user = Users.query.get(1)
print(f'查询到的数据:{user}')
return {
"code": 0,
"msg": "success",
"data": marshal(user, user_fields)
}

这样就可以返回自己定义的json格式

{
"code": 0,
"msg": "success",
"data": {
"id": 1,
"username": "test",
"is_active": true
}
}

查询list对象

如果查询结果是一个list ,包含多个对象,使用 marshal() 函数也可以序列化

from flask_restful import Resource, fields, marshal_with, marshal

user_fields = {
'id': fields.Integer,
'username': fields.String,
'is_active': fields.Boolean
}


class UserInfo(Resource):

def get(self):
user = Users.query.all() # 查询多个
print(f'查询到的数据:{user}')
return {
"code": 0,
"msg": "success",
"data": marshal(user, user_fields)
}

接口返回内容

{
"code": 0,
"msg": "success",
"data": [
{
"id": 1,
"username": "test",
"is_active": true
},
{
"id": 2,
"username": "test1",
"is_active": true
},
{
"id": 3,
"username": "test3",
"is_active": true
},
{
"id": 5,
"username": "test5",
"is_active": true
}
]
}