安全监测系统 06 Flask restful 定制返回的JSON格式

Extending Flask-RESTful — Flask-RESTful 0.3.8 documentation

目标:我们希望将原先的响应信息

{
    "status_level_list": [
        {
            "id": 101,
            "name": "健康"
        },
        {
            "id": 111,
            "name": "轻度"
        },
        {
            "id": 121,
            "name": "中度"
        },
        {
            "id": 131,
            "name": "重度"
        }
    ]
}

封装一层:

{

        “message”:“ok”

        “data”:{ 

                 返回的具体内容

        }

}

{
    "message": "OK",
    "data": {
        "status_level_list": [
            {
                "id": 101,
                "name": "健康"
            },
            {
                "id": 111,
                "name": "轻度"
            },
            {
                "id": 121,
                "name": "中度"
            },
            {
                "id": 131,
                "name": "重度"
            }
        ]
    }
}

实现:

步骤一:创建 common/utils/output.py 工具, 定义output_json函数

from flask import make_response, current_app, request
from flask_restful.utils import PY3
from json import dumps


def output_json(data, code, headers=None):
    """Makes a Flask response with a JSON encoded body"""
    if str(code) == '400':
        current_app.logger.warn(request.headers)
        current_app.logger.warn(request.data)
        current_app.logger.warn(str(data))

    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

步骤二 :在Api对象上声明 

level_api.representation('application/json')(output_json)

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值