comment—utils—output.py
from flask import make_response, current_app
from flask_restful.utils import PY3
from json import dumps
# todo 将字典格式的响应数据转化为json格式的响应数据
def output_json(data, code, headers=None):
"""Makes a Flask response with a JSON encoded body"""
#todo 此处添加自己定义的json格式规则,把返回给前端的数据做一个封装,以便于前端可以使用统一的规则解析数据
if 'message' not in data:
data = {
# 'message':'OK',
'code': 200, # 自动的将状态200封装到json中
'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
#todo 将字典转化为json
dumped = dumps(data, **settings) + "\n"
resp = make_response(dumped, code)
resp.headers.extend(headers or {})
return resp
使用:在资源视图中(创建蓝图的py文件中)定义
user_api.representation('aplication/json')(output_json)
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/74123.html