声明,在Linux环境下,安装python ,flask,以及flask restful
1.例子 一:保存为app1.py文件
<span style="font-family:Comic Sans MS;font-size:14px;">from flask import Flask
from flask.ext import restful
app = Flask(__name__)
api = restful.Api(app)
class HelloWorld(restful.Resource):
def get(self):
return {'hello': 'world'}
api.add_resource(HelloWorld, '/')
if __name__ == '__main__':
app.run(debug=True)</span>
命令行,运行<span style="font-family:Comic Sans MS;font-size:14px;"> python api.py
* Running on http://127.0.0.1:5000/
打开另外一个命令行界面:输入 curl http://127.0.0.1/ 出现如下结果:
curl http://127.0.0.1:5000/
{"hello": "world"}</span><span style="font-family:Comic Sans MS;font-size:14px;">
</span>
心得
- api.add_resource(HelloWorld, '/'),add_resource函数添加类HelloWorld
- curl时,返回{'hello': 'world'},默认是GET
- -X后面的命令不分大小写
证例结果:
<span style="font-family:Comic Sans MS;font-size:14px;"> curl http://127.0.0.1:5000
{
"hello": "world"
}
curl http://127.0.0.1:5000 -X GET
{
"hello": "world"
}
curl http://127.0.0.1:5000 -X get
{
"hello": "world"
}
curl http://127.0.0.1:5000 -X Get
{
"hello": "world"
}</span>
2.例子
<span style="font-family:Comic Sans MS;font-size:14px;">
Flask-RESTful 提供的最主要的基础就是资源(resources)
api_Routing.py
复制代码
from flask import Flask, request
from flask.ext.restful import Resource, Api
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_id1
api.add_resource(TodoSimple, '/<string:todo_id>')
if __name__ == '__main__':
app.run(debug=True)</span>
运行:
<span style="font-family:Comic Sans MS;font-size:14px;">$ python api_Routing.py
* Running on http://127.0.0.1:5000/
另一命令窗口
jihite@ubuntu:~$ curl http://127.0.0.1:5000/todo1 -d 'data=apple' -X PUT
{
"todo1": "apple"
}
jihite@ubuntu:~$ curl http://127.0.0.1:5000/todo1
{
"todo1": "apple"
}
jihite@ubuntu:~$ curl http://127.0.0.1:5000/todo2 -d 'data=banana' -X PUT
{
"todo2": "banana"
}
jihite@ubuntu:~$ curl http://127.0.0.1:5000/todo2
{
"todo2": "banana"
}</span>
心得
- -d 是增加数据的参数
- 因put函数中request.form['data']找'data'这一项,所有-d 后面的数据必须有 data=
证例如下
1
2
3
4
5
6
7
8
9
10
11
12
|
jihite@ubuntu:~$ curl http:// 127.0 . 0.1: 5000 /todo 1 -d 'data=jimi' -X PUT
{
"todo1" : "jimi"
}
jihite@ubuntu:~$ curl http:// 127.0 . 0.1: 5000 /todo 1 -X GET
{
"todo1" : "jimi"
}
jihite@ubuntu:~$ curl http:// 127.0 . 0.1: 5000 /todo 1 -d 'task=jimi' -X PUT
{
"message" : "The browser (or proxy) sent a request that this server could not understand." #server无法理解请求
}
|
多种类型的返回值
api_mulout.py
from flask import Flask, request from flask.ext.restful import Resource, Api app = Flask(__name__) api = Api(app) todos = {} class Todo1(Resource): def get(self): return {'task': 'apple'} class Todo2(Resource): def get(self): return {'task': 'babana'}, 201 class Todo3(Resource): def get(self): return {'task': 'pear'}, 201, {'data': 'peach'} api.add_resource(Todo1, '/Todo1') api.add_resource(Todo2, '/Todo2') api.add_resource(Todo3, '/Todo3') if __name__ == "__main__": app.run(debug=True)
运行
1
2
3
|
$ python api_mulout.py
* Running on http:// 127.0 . 0.1: 5000 / (Press CTRL+C to quit)
* Restarting with stat
|
另一命令行窗口
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
jihite@ubuntu:~/project/flask$ curl http:// 127.0 . 0.1: 5000 /Todo 1
{
"task" : "apple"
}
jihite@ubuntu:~/project/flask$ curl http:// 127.0 . 0.1: 5000 /Todo 2
{
"task" : "babana"
}
jihite@ubuntu:~/project/flask$ curl http:// 127.0 . 0.1: 5000 /Todo 3
{
"task" : "pear"
}
jihite@ubuntu:~/project/flask$ curl http:// 127.0 . 0.1: 5000 /Todo 4
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN" >
<title> 404 Not Found</title>
<h 1 >Not Found</h 1 >
<p>The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.</p>
|
心得
- api.add_resource通过第二个参数关联第一个参数指定的类
多URL访问同一个资源
api_points.py
from flask import Flask from flask.ext import restful app = Flask(__name__) api = restful.Api(app) class HelloWorld(restful.Resource): def get(self): return {'hello': 'world'} api.add_resource(HelloWorld, '/', '/hello') if __name__ == '__main__': app.run(debug=True)
运行
1
2
3
|
$ python api_points.py
* Running on http:// 127.0 . 0.1: 5000 / (Press CTRL+C to quit)
* Restarting with stat
|
另一个命令窗口执行
完整案例
whole.py
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)