flask-restful中自定义json数据的方法
我们在实际开发中, 返回的JSON数据中除了包含基础数据, 往往还需要设置一些 统一的外层包装, 以便前端进行更好的解析处理, 如:
{
"message": "ok", // 外层包装
"code": 200, // 外层包装
"data": { // 基础数据
"name": "张三",
"age": 20
}
}
- flask-restful 提供了 api.representation()装饰器方法, 允许开发者自定义返回的数据格式
- 在实现自定义JSON格式时, 可以参考 flask-restful 默认转换函数 (字典转json数据) 的源代码
默认转换函数的源代码:
# flask_restful/representations/json.py
def output_json(data, code, headers=None):
"""Makes a Flask response with a JSON encoded body"""
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
代码示例:
from collections import OrderedDict
from json import dumps
from flask import Flask, current_app, make_response, Response
from flask_restful 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('RESTFUL_JSON', {})
if current_app.debug:
settings.setdefault('indent', 4)
settings.setdefault('sort_keys', not PY3)
# 添加json外层包装
if 'message' not in data: # 判断是否设置了自定义的错误信息
data = {
'message': 'ok',
'data': data
}
# 字典转json字符串
dumped = dumps(data, **settings) + "\n"
# 构建响应对象
resp = make_response(dumped, code)
resp.headers.extend(headers or {})
return resp
class DemoResource(Resource):
def get(self):
return {'foo': "get"}
def post(self):
return {'message': 'parameter error: name', "data": None}
api.add_resource(DemoResource, '/')
if __name__ == '__main__':
app.run(debug=True)
- 我们在实际开发中, 可能还会展开装饰器来设置自定义响应格式
代码示例:
def output_json(data, code, headers=None):
"""自定义json形式"""
# 根据flask内置配置, 进行格式处理(缩进/key是否排序等)
settings = current_app.config.get('RESTFUL_JSON', {})
if current_app.debug:
settings.setdefault('indent', 4)
settings.setdefault('sort_keys', not PY3)
# 添加json外层包装
if 'message' not in data: # 判断是否设置了自定义的错误信息
data = {
'message': 'ok',
'data': data
}
# 字典转json字符串
dumped = dumps(data, **settings) + "\n"
# 构建响应对象
resp = make_response(dumped, code)
resp.headers.extend(headers or {})
return resp
# 展开装饰器的形式设置自定义响应形式
api.representation('application/json')(output_json)