【Flask】RESTful的响应处理
生活随笔
收集整理的這篇文章主要介紹了
【Flask】RESTful的响应处理
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1、序列化數據(返回字典格式的數據)
Flask-RESTful 提供了marshal工具,用來幫助我們將數據序列化為特定格式的字典數據,以便作為視圖的返回值。
使用裝飾器的方式
不使用裝飾器的方式
from flask import Flask from flask_restful import Resource,Api,marshal_with,marshal,fieldsapp=Flask(__name__)#步驟一:創建restful的api api=Api(app)# 用來模擬要返回的數據對象的類 class User(object):def __init__(self,username,password,userid):self.username=usernameself.password=passwordself.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字段
對于諸如此類的接口,能否在某處統一格式化成上述需求格式?
{"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/1262dumped = 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}訪問資源
總結
以上是生活随笔為你收集整理的【Flask】RESTful的响应处理的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Flask】Flask-RESTful
- 下一篇: 【Flask】ORM多对多关联关系