加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

flask-序列化

发布时间:2020-12-20 10:55:30 所属栏目:Python 来源:网络整理
导读:序列化 示例代码 from flask import Flaskfrom flask_restful import Resource,Api,marshal,fields,marshal_withapp = Flask(__name__)api = Api(app)class User: def __init__(self): self.name = '张三' self.age = 20 self.height = 1.8 self.scores = [8

序列化

示例代码

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)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读