日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

【Flask】RESTful的响应处理

發(fā)布時(shí)間:2025/3/21 编程问答 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【Flask】RESTful的响应处理 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

1、序列化數(shù)據(jù)(返回字典格式的數(shù)據(jù))

Flask-RESTful 提供了marshal工具,用來幫助我們將數(shù)據(jù)序列化為特定格式的字典數(shù)據(jù),以便作為視圖的返回值。
使用裝飾器的方式

from flask import Flask from flask_restful import Resource,Api,marshal_with,marshal,fieldsapp=Flask(__name__)#步驟一:創(chuàng)建restful的api api=Api(app)# 用來模擬要返回的數(shù)據(jù)對象的類 class User(object):def __init__(self,username,password,userid):self.username=usernameself.password=passwordself.userid=userid#為了把模型對象轉(zhuǎn)換為字典,在marshal里面必須定義一個(gè)屬性轉(zhuǎn)化格式 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中,才可以發(fā)布 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,fieldsapp=Flask(__name__)#步驟一:創(chuàng)建restful的api api=Api(app)# 用來模擬要返回的數(shù)據(jù)對象的類 class User(object):def __init__(self,username,password,userid):self.username=usernameself.password=passwordself.userid=userid#為了把模型對象轉(zhuǎn)換為字典,在marshal里面必須定義一個(gè)屬性轉(zhuǎn)化格式 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中,才可以發(fā)布 api.add_resource(HelloRescore,'/hello')if __name__ == '__main__':app.run(debug=True)

對比下面兩種寫法:
@marshal_with(property_fields,envelope='data')

@marshal_with(property_fields)

如果加上參數(shù)envelope=‘data’,會(huì)變成嵌套的字典格式

2、定制返回的JSON格式

需求
想要接口返回的JSON數(shù)據(jù)具有如下統(tǒng)一的格式
{"message": "描述信息", "data": {要返回的具體數(shù)據(jù)}}
在接口處理正常的情況下, message返回ok即可,但是若想每個(gè)接口正確返回時(shí)省略message字段

class DemoResource(Resource): def get(self): return {'user_id':1, 'name': 'hello'}

對于諸如此類的接口,能否在某處統(tǒng)一格式化成上述需求格式?
{"message": "OK", "data": {'user_id':1, 'name': 'hello'}}
解決

Flask-RESTful的Api對象提供了一個(gè)representation的裝飾器,允許定制返回?cái)?shù)據(jù)的呈現(xiàn)格式

將字典格式的響應(yīng)數(shù)據(jù)轉(zhuǎn)化為json格式的響應(yīng)數(shù)據(jù)

#todo 將字典格式的響應(yīng)數(shù)據(jù)轉(zhuǎn)化為json格式的響應(yīng)數(shù)據(jù) @api.representation('application/json') def output_json(data, code, headers=None):"""Makes a Flask response with a JSON encoded body"""#此處添加自己定義的json格式規(guī)則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格式規(guī)則

if 'message' not in data:data={'message':'OK','data':data}

訪問資源

總結(jié)

以上是生活随笔為你收集整理的【Flask】RESTful的响应处理的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。