flask-自定义json

自定义json

1552472-20190820193731622-1580279574.png

from flask import Flask
from flask_restful import Resource, Api
from flask import make_response, current_app
from flask_restful.utils import PY3
from json import dumps

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
        }

class DemoResource(Resource):
    def get(self):
        user = User()
        return user.to_dict()

    def post(self):
        return {'message': 'param error: username', 'data': None}

api.add_resource(DemoResource, '/index')


@api.representation('application/json')  # 让json形式数据使用指定的函数进行格式转换
def output_json(data, code, headers=None):
    """Makes a Flask response with a JSON encoded body"""

    """对于返回的字典进行自定义格式的包装"""
    if 'message' not in data:
        data = {
            'message': 'ok',
            'data': data
        }

    settings = current_app.config.get('RESTFUL_JSON', {})

    # If we're in debug mode, and the indent is not set, we set it to a
    # reasonable value here.  Note that this won't override any existing value
    # that was set.  We also set the "sort_keys" value.
    if current_app.debug:
        settings.setdefault('indent', 4)
        settings.setdefault('sort_keys', not PY3)

    # always end the json dumps with a new line
    # see https://github.com/mitsuhiko/flask/pull/1262
    dumped = dumps(data, **settings) + "\n"

    resp = make_response(dumped, code)
    resp.headers.extend(headers or {})
    return resp


if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0')

转载于:https://www.cnblogs.com/oklizz/p/11385100.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值