Flask-RESTful 快速入门
是時候編寫你第一個 REST API。本指南假設(shè)你對 Flask 有一定的認識,并且已經(jīng)安裝了 Flask 和 Flask-RESTful。
一個最小的 API
一個最小的 Flask-RESTful API 像這樣:
from flask import Flask from flask_restful import Api, Resourceapp = Flask(__name__) api = Api(app)class HelloWorld(Resource):def get(self):return {'hello': 'world'}api.add_resource(HelloWorld, '/')if __name__ == '__main__':app.run(debug=True)資源豐富的路由(Resourceful Routing)
Flask-RESTful 提供的最主要的基礎(chǔ)就是資源(resources)。
資源(Resources)是構(gòu)建在 Flask 可拔插視圖 之上,只要在你的資源(resource)上定義方法就能夠容易地訪問多個 HTTP 方法。
一個待辦事項應(yīng)用程序的基本的 CRUD 資源看起來像這樣:
todos = {}class TodoSimple(Resource):def get(self, todo_id):return {todo_id: todos[todo_id]}def put(self, todo_id):todos[todo_id] = request.form['data']return {todo_id: todos[todo_id]}api.add_resource(TodoSimple, '/<string:todo_id>')
Flask-RESTful 支持視圖方法多種類型的返回值。同 Flask 一樣,你可以返回任一迭代器,它將會被轉(zhuǎn)換成一個包含原始 Flask 響應(yīng)對象的響應(yīng)。
Flask-RESTful 也支持使用多個返回值來設(shè)置響應(yīng)代碼和響應(yīng)頭,如下所示:
class Todo1(Resource):def get(self):# Default to 200 OKreturn {'task': 'Hello world'}class Todo2(Resource):def get(self):# Set the response code to 201return {'task': 'Hello world'}, 201class Todo3(Resource):def get(self):# Set the response code to 201 and return custom headersreturn {'task': 'Hello world'}, 201, {'Etag': 'some-opaque-string'}端點(Endpoints)
很多時候在一個 API 中,你的資源可以通過多個 URLs 訪問。你可以把多個 URLs 傳給 Api 對象的 Api.add_resource() 方法。每一個 URL 都能訪問到你的 Resource。
api.add_resource(HelloWorld,'/','/hello')你也可以為你的資源方法指定 endpoint 參數(shù)。
api.add_resource(Todo,'/todo/<int:todo_id>', endpoint='todo_ep')參數(shù)解析
盡管 Flask 能夠簡單地訪問請求數(shù)據(jù)(比如查詢字符串或者 POST 表單編碼的數(shù)據(jù)),驗證表單數(shù)據(jù)仍然很痛苦。
Flask-RESTful 內(nèi)置了支持驗證請求數(shù)據(jù),它使用了一個類似 argparse 的庫。
parser = reqparse.RequestParser() parser.add_argument('rate', type=int, help='Rate to charge for this resource') args = parser.parse_args()需要注意地是與 argparse 模塊不同,reqparse.RequestParser.parse_args() 返回一個 Python 字典而不是一個自定義的數(shù)據(jù)結(jié)構(gòu)。
使用 reqparse 模塊同樣可以自由地提供聰明的錯誤信息。如果參數(shù)沒有通過驗證,Flask-RESTful 將會以一個 400 錯誤請求以及高亮的錯誤信息回應(yīng)。
inputs 模塊提供了許多的常見的轉(zhuǎn)換函數(shù),比如 inputs.date() 和 inputs.url()。
使用 strict=True 調(diào)用 parse_args 能夠確保當請求包含你的解析器中未定義的參數(shù)的時候會拋出一個異常。
args = parser.parse_args(strict=True)數(shù)據(jù)格式化
默認情況下,在你的返回迭代中所有字段將會原樣呈現(xiàn)。
盡管當你剛剛處理 Python 數(shù)據(jù)結(jié)構(gòu)的時候,覺得這是一個偉大的工作,但是當實際處理它們的時候,會覺得十分沮喪和枯燥。
為了解決這個問題,Flask-RESTful 提供了 fields 模塊和 marshal_with() 裝飾器。
類似 Django ORM 和 WTForm,你可以使用 fields 模塊來在你的響應(yīng)中格式化結(jié)構(gòu)。
from collections import OrderedDict from flask.ext.restful import fields, marshal_withresource_fields = {'task': fields.String,'uri': fields.Url('todo_ep') }class TodoDao(object):def __init__(self, todo_id, task):self.todo_id = todo_idself.task = task# This field will not be sent in the responseself.status = 'active'class Todo(Resource):@marshal_with(resource_fields)def get(self, **kwargs):return TodoDao(todo_id='my_todo', task='Remember the milk')上面的例子接受一個 python 對象并準備將其序列化。marshal_with() 裝飾器將會應(yīng)用到由 resource_fields 描述的轉(zhuǎn)換。
從對象中提取的唯一字段是 task。
fields.Url 域是一個特殊的域,它接受端點(endpoint)名稱作為參數(shù)并且在響應(yīng)中為該端點生成一個 URL。
許多你需要的字段類型都已經(jīng)包含在內(nèi)。
總結(jié)
以上是生活随笔為你收集整理的Flask-RESTful 快速入门的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 2013\National _C_C++
- 下一篇: Label Studio 入门