【Flask】RESTful的响应处理

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
        }

访问资源
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

敲代码敲到头发茂密

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值