flask-restful中自定义json数据的方法
我们在实际开发中, 返回的JSON数据中除了包含基础数据, 往往还需要设置一些 统一的外层包装, 以便前端进行更好的解析处理, 如:
{
"message": "ok", // 外层包装
"code": 200, // 外层包装
"data": { // 基础数据
"name": "张三",
"age": 20
}
}
- flask-restful 提供了 api.representation()装饰器方法, 允许开发者自定义返回的数据格式
- 在实现自定义JSON格式时, 可以参考 flask-restful 默认转换函数 (字典转json数据) 的源代码
output_json封装的方法:
from flask_restful.representations.json import output_json
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
代码示例:
# 使用output_json
@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 'msg' 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 User(Resource):
def __init__(self, id, name, age, phone, account):
self.uid = id
self.name = name
self.age = age
self.phone = phone
self.account = account
class UserInfo(Resource):
def get(self):
user = User(1, '暴龙战士', 20, '17630000000', '暴龙战士')
data = {
'id': user.uid,
'name': user.name,
}
return data
api.add_resource(UserInfo, '/info')