序列化
示例代码
from flask import Flask
from flask_restful import Resource, Api, marshal, fields, marshal_with
app = Flask(__name__)
api = Api(app)
class User:
def __init__(self):
self.name = '张三'
self.age = 20
self.height = 1.8
self.scores = [80, 75]
self.info = {
'gender': True
}
def to_dict(self): # 模型的属性转为字典的键值对
return {
'username': self.name,
'age': self.age
}
# 定义序列化的转换规则
user_fields = {
"username": fields.String(attribute='name'), # attribute设置字段对应的属性名
'age': fields.Integer,
'weight': fields.Float(default=75.3), # default取不出属性值时,可以使用默认值
'scores': fields.List(fields.Integer),
'info': fields.Nested({'gender': fields.Boolean})
}
class DemoResource(Resource):
method_decorators = {'post': [marshal_with(user_fields)]}
def get(self):
user = User()
# 对模型对象进行序列化转换 返回dict
data = marshal(user, user_fields, envelope='data')
return data
def post(self):
user = User()
# 如果使用marshal_with装饰器, 则可以直接返回模型对象
return user
def put(self):
user = User()
return user.to_dict() # 使用自定义方法来转换模型数据
api.add_resource(DemoResource, '/')
if __name__ == '__main__':
app.run(debug=True)