flask-restful-响应处理
响应处理
1、序列化数据marchal工具,定义字典数据
装饰器形式marshal_with(fields,envelope='信封')
marshal(data,fields,envelop='')
1 #Flask-RESTful 响应处理 2 #1、marshal 序列化数据 3 from flask import Flask 4 from flask_restful import Api,Resource,marshal,marshal_with,fields 5 app = Flask(__name__) 6 api = Api(app) 7 #让后端返回的数据可以序列化 8 class User(object): 9 def __init__(self,user_id,mobile,name): 10 self.user_id = user_id 11 self.mobile = mobile 12 self.name = name 13 #序列化容器 14 resource_data = { 15 'user_id':fields.Integer, 16 'mobile':fields.String, 17 'name':fields.String 18 } 19 20 21 class respResource(Resource): 22 @marshal_with(resource_data,envelope='data') 23 def get(self): 24 #return {'data':'hello'} 25 user = User('2022','13209880988','xh') 26 #return user 27 return marshal(user,resource_data) 28 api.add_resource(respResource,'/index') 29 30 if __name__ == '__main__': 31 app.run(debug=True)
运行结果 使用postman工具
2、统一数据的json格式
找到flask-restful源码中的output_json函数
重写返回数据的方法data进行嵌套处理
手动调用装饰器
1 #统一数据交互的格式:返回json格式 2 from flask import Flask 3 from flask_restful import Api,Resource 4 app = Flask(__name__) 5 api = Api(app) 6 7 from flask import make_response,current_app 8 from flask_restful.utils import PY3 9 from json import dumps 10 11 @api.representation('application/json') 12 def output_json(data,code,headers=None): 13 settings = current_app.config.get('RESTFUL_JSON',{}) 14 if 'message' not in data: 15 data = { 16 'message':'OK', 17 'data':data 18 } 19 if current_app.debug: 20 settings.setdefault('indent',4) 21 settings.setdefault('sort_keys',not PY3) 22 dumped = dumps(data,**settings)+"\n" 23 24 resp = make_response(dumped,code) 25 resp.headers.extend(headers or {}) 26 return resp 27 class JsonResource(Resource): 28 def get(self): 29 return {'data':'hello'} 30 api.add_resource(JsonResource,'/') 31 if __name__ == '__main__': 32 app.run()
运行结果