from flask import Flaskfrom flask_restful import Resource,APIfrom flask import make_response,current_appfrom flask_restful.utils import PY3from Json import dumpsapp = 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') # 让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 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 respif __name__ == '__main__': app.run(deBUG=True,host='0.0.0.0')总结
以上是内存溢出为你收集整理的flask-自定义json全部内容,希望文章能够帮你解决flask-自定义json所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)