安全监测系统 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)
版权声明:本文为weixin_41672684原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。