Flask入门笔记-17_自定义json

  • 有的时候我们不想直接返回给数据返回, 可能需要统一包装一下
  • 比如就像DJango中的分页器最后返回的一步, 包装了Response对象
from json import dumps

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

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

class Demo(Resource):
    def get(self):
        # 响应体, 状态码, 响应头
        return {'demo': "get"}, 200, {"Server": 'test'}

    def post(self):
        return {
            'data': '',
            "errmsg": 'database error'
        }

@api.representation('application/json')  # 指定响应类型对应的转换操作
def output_json(data, code, headers=None):
    """Makes a Flask response with a JSON encoded body"""

    """自定义json处理"""
    if "data" not in data:
        data = {
            'data': data,
            'errmsg': 'ok'
        }

    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.add_resource(Demo, '/')

if __name__ == '__main__':
    app.run(host='0.0.0.0', port='8000')