Flask-RESTful是一个Flask扩展,可以用其快速构件REST APIs,也可以用其与现有的ORM/库协同工作
使用 pip install flask-restful
安装即可。
注意:某些Flask版本下,引入模块时采用from flask.ext.restful import Api
出错,则可以使用from flask_restful import Api
实现
from flask import Flask
from flask_restful import Api, Resource
app = 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)
在以上代码中,在设置师徒函数的路由时,则不使用之前那种装饰器route的方式,而是先封装一个视图类(即可插拔视图),再用api将其添加为服务器资源。
如此,在访问127.0.0.1:5000/时,服务器则会返回给客户端一个HelloWorld的字典。
以上,在可插拔视图类中定义了一个get方法,由此可推断,只需在其中定义更多的HTTP访问方式的类,即可实现多种HTTP访问动作。从而实现资源基本的 CRUD (增删改查)。
from flask import Flask
from flask import request
from flask_restful import Api, Resource
app = Flask(__name__)
api = Api(app)
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>')
if __name__ == '__main__':
app.run(debug=True)
如此,可以运行代码,在命令行下进行测试
(py3) python@ubuntu:~/Desktop/rest$ curl http://localhost:5000/todo1 -d 'data=Remember the milk' -X PUT
{
"todo1": "Remember the milk"
}
(py3) python@ubuntu:~/Desktop/rest$ curl http://localhost:5000/todo1 GET
{
"todo1": "Remember the milk"
}
亦可利用request库在python shell下测试
**>>> from requests import put,get
>>> put('http://127.0.0.1:5000/todo2',data={'data':'Remember the bbb'})
<Response [200]>
>>> put('http://127.0.0.1:5000/todo2',data={'data':'Remember the bbb'}).json()
{'todo2': 'Remember the bbb'}
>>>
**
rest的api可返回多个参数:
class Todo1(Resource):
def get(self):
# 默认200为正常返回状态码
return {'key':'value'}
class Todo2(Resource):
def get(self):
# 设置201为正常返回状态码
return {'key':'value'},201
class Todo1(Resource):
def get(self):
# 返回多个参数
return {'key':'value'},201,{'k':'v'}
也可为同一视图设置多个路由
# 把多个Urls传给同一个api对象
api.add_resource(TodoSimple,'/','h')
对于带参数的请求,参数的解析
在POST或PUT请求中,直接访问form表单并验证的工作有些麻烦。Flask-RESTful提供了”reqparse”库来简化。
前辈博文有详述:
http://blog.csdn.net/qq_28877125/article/details/77371065
例如:
from flask_restful import reqparse
parser = reqparse.RequestParser()
parser.add_argument('rate',type=int,help='Rate to charge for this resource')
parser.add_argument(””)方法可以对参数加以约束
在请求时使用args = parser.parse_args()
即可验证(返回一个字典)
官方文档中的一个程序例子
from flask import Flask
from flask.ext.restful import reqparse, abort, Api, Resource
app = Flask(__name__)
api = Api(app)
TODOS = {
'todo1': {'task': 'build an API'},
'todo2': {'task': '?????'},
'todo3': {'task': 'profit!'},
}
def abort_if_todo_doesnt_exist(todo_id):
if todo_id not in TODOS:
abort(404, message="Todo {} doesn't exist".format(todo_id))
parser = reqparse.RequestParser()
parser.add_argument('task', type=str)
# Todo
# show a single todo item and lets you delete them
class Todo(Resource):
def get(self, todo_id):
abort_if_todo_doesnt_exist(todo_id)
return TODOS[todo_id]
def delete(self, todo_id):
abort_if_todo_doesnt_exist(todo_id)
del TODOS[todo_id]
return '', 204
def put(self, todo_id):
args = parser.parse_args()
task = {'task': args['task']}
TODOS[todo_id] = task
return task, 201
# TodoList
# shows a list of all todos, and lets you POST to add new tasks
class TodoList(Resource):
def get(self):
return TODOS
def post(self):
args = parser.parse_args()
todo_id = int(max(TODOS.keys()).lstrip('todo')) + 1
todo_id = 'todo%i' % todo_id
TODOS[todo_id] = {'task': args['task']}
return TODOS[todo_id], 201
##
## Actually setup the Api resource routing here
##
api.add_resource(TodoList, '/todos')
api.add_resource(Todo, '/todos/<todo_id>')
if __name__ == '__main__':
app.run(debug=True)