概括
- URL:需要操作的对象,也就是资源
- HTTP method:我要对该对象做什么(POST 增、DELETE 删、GET 查、PUT 和 PATCH 改)
- HTTP status code:操作的结果
做到这个,就达成了 REST 的第二层。
视图的定义方式
一般视图都使用 app.route()
装饰器定义,但是这种方式显然不适合用于定义 restful api.
对于 restful 场景,flask 提供了 MethodView 类,可以用基于类的方法来定义视图函数:
class HttpMethodExample(MethodView):
def get(self):
return 'Send request with `GET` method'
def post(self):
return 'Send request with `POST` method'
def put(self):
return 'Send request with `PUT` method'
def patch(self):
return 'Send request with `PATCH` method'
def delete(self):
return 'Send request with `DELETE` method'
# 基于 MethodView 构造视图函数
example_view = HttpMethodExample.as_view('http_method_example2')
# 为该视图函数添加 url 规则
app.add_url_rule('/http-method-test2/', view_func=example_view)
flask 还提供了 jsonify 与 request.get_json() 用于序列化与反序列化数据。
flask-restplus
flask-restplus 是 flask-restful 的一个 fork 项目,对比文档你可以发现它俩有九分相似。flask-restplus 的优势在于它提供 API 文档自动生成的功能。
待续。。。