Flask 学习-57.Flask-RESTX 定制返回统一的JSON格式

前言

一般在接口开发中,会定制统一的返回JSON 格式如:{'code': 0, 'message': 'success', 'data': {}}

定制JSON 格式

Flask-RESTX 的Api对象提供了一个representation的装饰器,允许定制返回数据的呈现格式

基本示例

api = Api(app)
 
@api.representation('application/json')
def output_json(data, code, headers):
    # TODO ..... 添加自定义处理
    return resp

flask_restful.representations.py文件源码中有一个output_json 方法

def output_json(data, code, headers=None):
    """Makes a Flask response with a JSON encoded body"""

    settings = current_app.config.get("RESTX_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.
    if current_app.debug:
        settings.setdefault("indent", 4)

    # 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.representation() 重新定义输出格式

from six import PY3


@api.representation('application/json')  # 指定响应形式对应的转换函数
def output_json(data, code, headers=None):
    """自定义json形式"""
    # 根据flask内置配置, 进行格式处理(缩进/key是否排序等)
    settings = current_app.config.get('RESTX_JSON', {})

    if current_app.debug:
        settings.setdefault('indent', 4)
        settings.setdefault('sort_keys', not PY3)

    # *****------start---------此处是新增代码---------********
    if 'message' not in data:  # 判断是否设置了自定义的错误信息
        data = {
            'code': 0,
            'message': 'success',
            'data': data
        }
    # *****-------end--------此处是新增代码---------********
    # 字典转json字符串
    dumped = dumps(data, **settings) + "\n"

    # 构建响应对象
    resp = make_response(dumped, code)
    resp.headers.extend(headers or {})
    return resp

完整示例代码

以下是完整的示例

from json import dumps
from flask import Flask, current_app, make_response, Response
from flask_restx import Resource, Api
from six import PY3

app = Flask(__name__)
api = Api(app)


@api.representation('application/json')  # 指定响应形式对应的转换函数
def output_json(data, code, headers=None):
    """自定义json形式"""
    # 根据flask内置配置, 进行格式处理(缩进/key是否排序等)
    settings = current_app.config.get('REST_JSON', {})

    if current_app.debug:
        settings.setdefault('indent', 4)
        settings.setdefault('sort_keys', not PY3)

    # *****------start---------此处是新增代码---------********
    if 'message' not in data:  # 判断是否设置了自定义的错误信息
        data = {
            'code': 0,
            'message': 'success',
            'data': data
        }
    # *****-------end--------此处是新增代码---------********
    # 字典转json字符串
    dumped = dumps(data, **settings) + "\n"

    # 构建响应对象
    resp = make_response(dumped, code)
    resp.headers.extend(headers or {})
    return resp


@api.route('/demo')
class DemoResource(Resource):

    def get(self):
        return {'id': "1"}

    def post(self):
        return {'message': 'success', "data": None}


if __name__ == '__main__':
    app.run()

测试get请求

posted @ 2022-09-07 15:15  上海-悠悠  阅读(681)  评论(0编辑  收藏  举报