同flask一樣,flask-restful同樣支持返回任一迭代器,它將會被轉換成一個包含原始 Flask 響應對象的響應:
class ArticleApi(Resource):def get(self):return {"hello":"world"},201,{"course":"python"}
在此基礎上還可以做一個靈活的拓展,假設我們根據發來的請求對數據庫進行了檢索,并將結果賦給名為student
的變量。如果搜索結果即最后的student
為空,則狀態碼為404,否則為200。比較pythonic的寫法為:
return {'student': student}, 200 if student is not None else 404
?
flask-restful為我們提供了一個方法去驗證請求參數:reqparse
from flask_restful import reqparse
class ArticleApi(Resource):def get(self):parse = reqparse.RequestParser()parse.add_argument("title_id",type=int,help="title參數的值只能是int類型!")# add_argument第一個參數代表請求的參數名稱,type表示限定請求的參數類型,實際做的是將參數進行強制轉換,如果可以就證明參數類型正確,help表示出錯后的提示信息。args = parse.parse_args(strict=True) # parse_args會接收reqparse驗證后的參數,以字典形式返回,strict=True表示限定參數只能是add_argument中添加的參數,否則返回400錯誤。print(args)return {"hello":"world"}
此時我們請求http://127.0.0.1:5000/v1/article/?title_id=abc:
當我們請求http://127.0.0.1:5000/v1/article/?title_id=1&id=1:
對于一個視圖函數,可以指定好一些字段用于返回。在使用ORM模型或者自定義模型時,他會自動獲取模型當中的相應字段,生成json數據返回給客戶端,我們需要導入flask_restful.marshl_with裝飾器,并且需要寫一個字典來指定需要返回的字段,以及該字段的數據類型:
article = Article.query.all()列表、
定義時
'article ': fields.List(fields.Nested(article _fields)),
?
?
article = Article.query.first() 對象
?
from flask_restful import fields,marshal_with
resource_fields = {"id":fields.Integer,"title":fields.String(default=None,attribute=None),# 在返回字段時有時候沒有值,我們可以使用default來設置一個默認值,例:default="默認標題"# 如果我們在返回字段時想要以"headline"作為標題名返回給用戶,但數據庫中對應的字段名是"title",這時候我們可以使用attribute配置這種映射,例:"headline":fields.String(attribute="title")"author_id":fields.String,"author":fields.Nested({ # Nested可以進行嵌套字段"username":fields.String,"phone":fields.String}),"tag":fields.List(fields.Nested({"id":fields.Integer,"name":fields.String}))}
class ArticleApi(Resource):@marshal_with(resource_fields)def get(self):article = Article.query.first()return article # 返回article時,flask_restful會自動讀取arctile模型上的id,title、author_id、tag以及author屬性,組成一個json字符串返回給客戶端。# 查找字段時,會使用article.id,article.title,article.author_id,article.author.username,article.author.phone,article.tag.id,article.tag.name進行查找
我們還可以通過繼承fields.Row來自定義字段類型:
# 自定義字段將輸出的小寫字母全部變為大寫
class UpperString(fields.Raw):def format(self, value):return value.upper()
resource_fields = {"value":UpperString
}
class ArticleApi(Resource):@marshal_with(resource_fields)def get(self):return {"value":"abc"}
api.add_resource(ArticleApi,"/article/",endpoint="article")
flask-restful返回Json格式的數據,但有時候我們要渲染html模版,返回html格式的數據,可以使用representation()裝飾器來實現:
@api.representation('text/html')
def output_html(data, code, headers=None):"""輸出函數有三個參數,data,code,以及 headers,data 是你從你的資源方法返回的對象,code 是預計的 HTTP 狀態碼,headers 是設置在響應中任意的 HTTP 頭。你的輸出函數應該返回一個 Flask 響應對象。"""print(data)response = make_response(data)return response
此時就可以返回html頁面了。
flask-restful還有一些中高級用法,具體可參考:http://www.pythondoc.com/Flask-RESTful/index.html。