Flask:API的一種簡易實現方式——MethodView

NO IMAGE

FlaskRESTful APIs 提供了一種簡易的實現方式,可以針對不同的HTTP方法提供不同的函式。使用也很簡單,只需要繼承 flask.views.MethodView 然後重寫需要的方法:GET POST PUT 等。

下面是官方給的程式示例:

from flask.views import MethodView
class UserAPI(MethodView):
def get(self):
users = User.query.all()
...
def post(self):
user = User.from_form_data(request.form)
...
app.add_url_rule('/users/', view_func=UserAPI.as_view('users'))

最下面的 add_url_rule 是新增路由,和用裝飾器的效果一樣:

@app.route('/users/')
def users(page):
users = User.query.all()
return render_template('users.html', users=users)

因為現在是檢視類而不是檢視函式,對類進行裝飾器操作沒有意義,如果想對檢視函式新增裝飾器,比如使用者登陸檢測,可以對 .as_view() 返回的函式進行裝飾:

def user_required(f):
"""Checks whether user is logged in or raises error 401."""
def decorator(*args, **kwargs):
if not g.user:
abort(401)
return f(*args, **kwargs)
return decorator
view = user_required(UserAPI.as_view('users'))
app.add_url_rule('/users/', view_func=view)

如何應對多種請求方法,比如使用者資訊管理:

URLMethodDescription
/users/GETGives a list of all users
/users/POSTCreates a new user
/users/idGETShows a single user
/users/idPUTUpdates a single user
/users/idDELETEDeletes a single user

官方給的實用小例子:

class UserAPI(MethodView):
def get(self, user_id):
if user_id is None:
# return a list of users
pass
else:
# expose a single user
pass
def post(self):
# create a new user
pass
def delete(self, user_id):
# delete a single user
pass
def put(self, user_id):
# update a single user
pass
user_view = UserAPI.as_view('user_api')
app.add_url_rule('/users/', defaults={'user_id': None},
view_func=user_view, methods=['GET',])
app.add_url_rule('/users/', view_func=user_view, methods=['POST',])
app.add_url_rule('/users/<int:user_id>', view_func=user_view,
methods=['GET', 'PUT', 'DELETE'])