序列化


示例代碼
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)