自定义json
from flask import Flask
from flask_restful import Resource, Api
from flask import make_response, current_app
from flask_restful.utils import PY3
from json import dumps
app = Flask(__name__)
api = Api(app)
class User:
def __init__(self):
self.name = '张三'
self.age = 20
self.height = 1.8
self.scores = [80, 75]
self.info = {
'gender': True
}
def to_dict(self):
return {
'username': self.name,
'age': self.age
}
class DemoResource(Resource):
def get(self):
user = User()
return user.to_dict()
def post(self):
return {'message': 'param error: username', 'data': None}
api.add_resource(DemoResource, '/index')
@api.representation('application/json')
def output_json(data, code, headers=None):
"""Makes a Flask response with a JSON encoded body"""
"""对于返回的字典进行自定义格式的包装"""
if 'message' not in data:
data = {
'message': 'ok',
'data': data
}
settings = current_app.config.get('RESTFUL_JSON', {})
if current_app.debug:
settings.setdefault('indent', 4)
settings.setdefault('sort_keys', not PY3)
dumped = dumps(data, **settings) + "\n"
resp = make_response(dumped, code)
resp.headers.extend(headers or {})
return resp
if __name__ == '__main__':
app.run(debug=True, host='0.0.0.0')
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步