1、序列化数据(返回字典格式的数据)
Flask-RESTful 提供了marshal工具,用来帮助我们将数据序列化为特定格式的字典数据,以便作为视图的返回值。
使用装饰器的方式
from flask import Flask
from flask_restful import Resource,Api,marshal_with,marshal,fields
app=Flask(__name__)
#步骤一:创建restful的api
api=Api(app)
# 用来模拟要返回的数据对象的类
class User(object):
def __init__(self,username,password,userid):
self.username=username
self.password=password
self.userid=userid
#为了把模型对象转换为字典,在marshal里面必须定义一个属性转化格式
property_fields={
'username':fields.String,
'password':fields.String
}
#步骤二:定义资源resource
class HelloRescore(Resource):
@marshal_with(property_fields,envelope='data')
def get(self):
user=User(username='zilv',password='123',userid='66')
return user
#步骤三:将资源加载到api中,才可以发布
api.add_resource(HelloRescore,'/hello')
if __name__ == '__main__':
app.run(debug=True)
不使用装饰器的方式
from flask import Flask
from flask_restful import Resource,Api,marshal_with,marshal,fields
app=Flask(__name__)
#步骤一:创建restful的api
api=Api(app)
# 用来模拟要返回的数据对象的类
class User(object):
def __init__(self,username,password,userid):
self.username=username
self.password=password
self.userid=userid
#为了把模型对象转换为字典,在marshal里面必须定义一个属性转化格式
property_fields={
'username':fields.String,
'password':fields.String
}
#步骤二:定义资源resource
class HelloRescore(Resource):
def get(self):
user=User(username='zilv',password='123',userid='66')
return marshal(user,property_fields)
#步骤三:将资源加载到api中,才可以发布
api.add_resource(HelloRescore,'/hello')
if __name__ == '__main__':
app.run(debug=True)
对比下面两种写法:
@marshal_with(property_fields,envelope='data')
@marshal_with(property_fields)
如果加上参数envelope=‘data’,会变成嵌套的字典格式
2、定制返回的JSON格式
需求
想要接口返回的JSON数据具有如下统一的格式
{"message": "描述信息", "data": {要返回的具体数据}}
在接口处理正常的情况下, message返回ok即可,但是若想每个接口正确返回时省略message字段
class DemoResource(Resource):
def get(self):
return {'user_id':1, 'name': 'hello'}
对于诸如此类的接口,能否在某处统一格式化成上述需求格式?
{"message": "OK", "data": {'user_id':1, 'name': 'hello'}}
解决
Flask-RESTful的Api对象提供了一个representation的装饰器,允许定制返回数据的呈现格式
将字典格式的响应数据转化为json格式的响应数据
#todo 将字典格式的响应数据转化为json格式的响应数据
@api.representation('application/json')
def output_json(data, code, headers=None):
"""Makes a Flask response with a JSON encoded body"""
#此处添加自己定义的json格式规则
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 resp
此处添加自己定义的json格式规则
if 'message' not in data:
data={
'message':'OK',
'data':data
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/74171.html