参考文档:https://www.cnblogs.com/Erick-L/p/7007090.html
当我们的视图要同时支持GET和POST请求时,视图类可以这么定义:
class MyMethodView(View):
methods = ['GET', 'POST']
def dispatch_request(self):
if request.method == 'GET':
return '<h1>Hello World!</h1>This is GET method.'
elif request.method == 'POST':
return '<h1>Hello World!</h1>This is POST method.'
app.add_url_rule('/mmview', view_func=MyMethodView.as_view('mmview'))
我们只需将需要支持的HTTP请求方法加入到视图类变量”methods”中即可。没加的话,默认只支持GET请求。
基于方法的视图
上节介绍的HTTP请求方法的支持,的确比较方便,但是对于RESTFul类型的应用来说,有没有更简单的方法,比如省去那些if, else判断语句呢?Flask中的”flask.views.MethodView”就可以做到这点,它是”flask.views.View”的子类。我们写个user API的视图吧:
from flask.views import MethodView
class UserAPI(MethodView):
def get(self, user_id):
if user_id is None:
return 'Get User called, return all users'
else:
return 'Get User called with id %s' % user_id
def post(self):
return 'Post User called'
def put(self, user_id):
return 'Put User called with id %s' % user_id
def delete(self, user_id):
return 'Delete User called with id %s' % user_id
现在我们分别定义了get, post, put, delete方法来对应四种类型的HTTP请求,注意函数名必须这么写。怎么将它绑定到路由上呢?
user_view = UserAPI.as_view('users')
# 将GET /users/请求绑定到UserAPI.get()方法上,并将get()方法参数user_id默认为None
app.add_url_rule('/users/', view_func=user_view, defaults={'user_id': None}, methods=['GET',])
# 将POST /users/请求绑定到UserAPI.post()方法上
app.add_url_rule('/users/', view_func=user_view, methods=['POST',])
# 将/users/<user_id>URL路径的GET,PUT,DELETE请求,
# 绑定到UserAPI的get(), put(), delete()方法上,并将参数user_id传入。
app.add_url_rule('/users/<user_id>', view_func=user_view, methods=['GET', 'PUT', 'DELETE'])
上例中”app.add_url_rule()”可以传入参数default,来设置默认值;参数methods,来指定支持的请求方法。
如果API多,有人觉得每次都要加这么三个路由规则太麻烦,可以将其封装个函数:
def register_api(view, endpoint, url, primary_id='id', id_type='int'):
view_func = view.as_view(endpoint)
app.add_url_rule(url, view_func=view_func,
defaults={primary_id: None},
methods=['GET',])
app.add_url_rule(url, view_func=view_func,
methods=['POST',])
app.add_url_rule('%s<%s:%s>' % (url, id_type, primary_id),
view_func=view_func,
methods=['GET', 'PUT', 'DELETE'])
register_api(UserAPI, 'users', '/users/', primary_id='user_id')
现在,一个”register_api()”就可以绑定一个API了
网友评论