flask-restful 快速入门

简介:

Flask-RESTful 是一个 Flask 扩展,它添加了快速构建 REST APIs 的支持。它当然也是一个能够跟你现有的ORM/库协同工作的轻量级的扩展。

快速入门

api.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, '/')

if __name__ == '__main__':
    app.run(debug=True)
复制代码

运行

1
2
$ python api.py
  * Running on http:// 127.0 . 0.1: 5000 /

另打开一个命令窗口,测试这个API:

1
2
$ curl http:// 127.0 . 0.1: 5000 /
{ "hello" "world" }

心得

  • api.add_resource(HelloWorld, '/'),add_resource函数添加类HelloWorld
  • curl时,返回{'hello': 'world'},默认是GET
  • -X后面的命令不分大小写

证例如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
jihite@ubuntu:~$ curl http:// 127.0 . 0.1: 5000
{
     "hello" "world"
}
jihite@ubuntu:~$ curl http:// 127.0 . 0.1: 5000  -X GET
{
     "hello" "world"
}
jihite@ubuntu:~$ curl http:// 127.0 . 0.1: 5000  -X get
{
     "hello" "world"
}
jihite@ubuntu:~$ curl http:// 127.0 . 0.1: 5000  -X Get
{
     "hello" "world"
}

资源丰富的路由

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_id]}

api.add_resource(TodoSimple, '/<string:todo_id>')

if __name__ == '__main__':
    app.run(debug=True)
复制代码

运行

1
2
$ python api_Routing.py
  * Running on http:// 127.0 . 0.1: 5000 /

另一命令窗口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
jihite@ubuntu:~$ curl http:// 127.0 . 0.1: 5000 /todo 1  -d  'data=apple'  -X PUT
{
     "todo1" "apple"
}
jihite@ubuntu:~$ curl http:// 127.0 . 0.1: 5000 /todo 1
{
     "todo1" "apple"
}
jihite@ubuntu:~$ curl http:// 127.0 . 0.1: 5000 /todo 2  -d  'data=banana'  -X PUT
{
     "todo2" "banana"
}
jihite@ubuntu:~$ curl http:// 127.0 . 0.1: 5000 /todo 2
{
     "todo2" "banana"
}

心得

  • -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

另一个命令窗口执行

1
2
3
4
5
6
7
8
jihite@ubuntu:~/project/flask$ curl http:// 127.0 . 0.1: 5000 /
{
     "hello" "world"
}
jihite@ubuntu:~/project/flask$ curl http:// 127.0 . 0.1: 5000 /hello
{
     "hello" "world"
}

完整案例

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)
复制代码

运行

1
2
3
$ python whole.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
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
jihite@ubuntu:~/project/flask$ curl http:// 127.0 . 0.1: 5000 /todos
{
     "todo1" : {
         "task" "build an API"
     },
     "todo2" : {
         "task" "?????"
     },
     "todo3" : {
         "task" "profit!"
     }
}
jihite@ubuntu:~/project/flask$ curl http:// 127.0 . 0.1: 5000 /todos/todo 2
{
     "task" "?????"
}
jihite@ubuntu:~/project/flask$ curl http:// 127.0 . 0.1: 5000 /todos -d  'task=hello'  -X POST -v
* Hostname was NOT found in DNS cache
*   Trying  127.0 . 0.1 ...
* Connected to  127.0 . 0.1  ( 127.0 . 0.1 ) port  5000  (# 0 )
> POST /todos HTTP/ 1.1
> User-Agent: curl/ 7.37 . 1
> Host:  127.0 . 0.1: 5000
> Accept: * /*
> Content-Length: 10
> Content-Type: application/x-www-form-urlencoded
>
* upload completely sent off: 10 out of 10 bytes
* HTTP 1.0, assume close after body
< HTTP/1.0 201 CREATED
< Content-Type: application/json
< Content-Length: 24
< Server: Werkzeug/0.10.4 Python/2.7.8
< Date: Tue, 14 Jul 2015 06:29:19 GMT
<
{
     "task": "hello"
}
* Closing connection 0
jihite@ubuntu:~/project/flask$ curl http://127.0.0.1:5000/todos
{
     "todo1": {
         "task": "build an API"
     },
     "todo2": {
         "task": "?????"
     },
     "todo3": {
         "task": "profit!"
     },
     "todo4": {
         "task": "hello"
     }
}
jihite@ubuntu:~/project/flask$ curl http://127.0.0.1:5000/todos/todo2 -X DELETE -v
* Hostname was NOT found in DNS cache
*   Trying 127.0.0.1...
* Connected to 127.0.0.1 (127.0.0.1) port 5000 (#0)
> DELETE /todos/todo2 HTTP/1.1
> User-Agent: curl/7.37.1
> Host: 127.0.0.1:5000
> Accept: */ *
>
* HTTP  1.0 , assume close after body
< HTTP/ 1.0  204  NO CONTENT
< Content-Type: application/json
< Content-Length:  0
< Server: Werkzeug/ 0.10 . 4  Python/ 2.7 . 8
< Date: Tue,  14  Jul  2015  06: 29: 37  GMT
<
* Closing connection  0
jihite@ubuntu:~/project/flask$ curl http:// 127.0 . 0.1: 5000 /todos
{
     "todo1" : {
         "task" "build an API"
     },
     "todo3" : {
         "task" "profit!"
     },
     "todo4" : {
         "task" "hello"
     }
}
jihite@ubuntu:~/project/flask$ curl http:// 127.0 . 0.1: 5000 /todos/todo 3  -d  'task=misi'  -X PUT -v
* Hostname was NOT found in DNS cache
*   Trying  127.0 . 0.1 ...
* Connected to  127.0 . 0.1  ( 127.0 . 0.1 ) port  5000  (# 0 )
> PUT /todos/todo 3  HTTP/ 1.1
> User-Agent: curl/ 7.37 . 1
> Host:  127.0 . 0.1: 5000
> Accept: */*
> Content-Length:  9
> Content-Type: application/x-www-form-urlencoded
>
* upload completely sent off:  9  out of  9  bytes
* HTTP  1.0 , assume close after body
< HTTP/ 1.0  201  CREATED
< Content-Type: application/json
< Content-Length:  23
< Server: Werkzeug/ 0.10 . 4  Python/ 2.7 . 8
< Date: Tue,  14  Jul  2015  06: 30: 24  GMT
<
{
     "task" "misi"
}
* Closing connection  0
jihite@ubuntu:~/project/flask$ curl http:// 127.0 . 0.1: 5000 / 4
{
     "todo1" : {
         "task" "build an API"
     },
     "todo3" : {
         "task" "misi"
     },
     "todo4" : {
         "task" "hello"
     }
}





本文转自jihite博客园博客,原文链接:http://www.cnblogs.com/kaituorensheng/p/4645080.html,如需转载请自行联系原作者
相关文章
|
3月前
|
JSON API 数据格式
构建RESTful APIs:使用Python和Flask
【4月更文挑战第9天】本文介绍了如何使用Python的Flask框架构建RESTful API。Flask是一个轻量级的Web应用框架,适合小型项目和微服务。首先,确保安装了Python和Flask,然后通过创建基本的Flask应用开始。接着,定义资源和路由,例如为“图书”资源创建GET、POST、PUT和DELETE方法的路由。使用`request`对象处理客户端数据,`jsonify`生成JSON响应。错误处理通过返回错误信息和相应HTTP状态码完成。最后,运行并测试API,发现Flask提供了一种简单高效的方式来构建RESTful APIs。
38 0
|
2月前
|
Python
python3之flask快速入门教程Demo
python3之flask快速入门教程Demo
47 6
|
2月前
|
JSON API 数据格式
如何使用Flask开发RESTful API
RESTful API(Representational State Transferful Application Programming Interface)是一种基于 REST 架构风格设计的 Web 服务接口,用于实现资源的增删改查(CRUD)操作。它通过使用 HTTP 协议的不同方法(如 GET、POST、PUT、DELETE)和 URL 路径来对资源进行操作,并使用不同的状态码和数据格式进行响应。
40 1
|
3月前
|
应用服务中间件 API nginx
使用Python和Flask构建RESTful Web API
使用Python和Flask构建RESTful Web API
51 0
|
3月前
|
缓存 API 数据库
构建高效Python Web应用:Flask框架与RESTful API设计原则
【5月更文挑战第20天】 在现代Web开发中,构建一个轻量级且高效的后端服务至关重要。本文将深入探讨如何使用Python的Flask框架结合RESTful API设计原则来创建可扩展和易于维护的Web应用程序。我们将通过分析Flask的核心特性,以及如何利用它来实现资源的合理划分、接口的版本控制和请求处理优化等,来指导读者打造高性能的API服务。文中不仅提供了理论指导,还包括了实践案例,旨在帮助开发者提升开发效率,并增强应用的稳定性和用户体验。
|
3月前
|
存储 缓存 监控
利用Python和Flask构建RESTful API的实战指南
在当今的软件开发中,RESTful API已成为前后端分离架构中的核心组件。本文将带你走进实战,通过Python的Flask框架,一步步构建出高效、安全的RESTful API。我们将从项目初始化、路由设置、数据验证、错误处理到API文档生成,全方位地探讨如何构建RESTful API,并给出一些实用的最佳实践和优化建议。
|
3月前
|
JSON 前端开发 API
Python和Flask构建简单的RESTful API
Python和Flask构建简单的RESTful API
|
3月前
|
JavaScript 前端开发 API
如何利用Python的Flask框架与Vue.js创建RESTful API服务
【4月更文挑战第10天】本文介绍了如何使用Flask和Vue.js创建一个前后端分离的RESTful API服务。Flask作为后端框架,负责提供CRUD操作,与SQLite数据库交互;Vue.js作为前端框架,构建用户界面并利用axios库与后端API通信。通过示例代码,展示了Flask设置路由处理用户数据以及Vue组件如何调用API获取和操作数据。此基础结构为构建更复杂的Web应用提供了起点。
83 4
|
3月前
|
JSON 安全 API
Flask-Login与Flask-RESTful:扩展你的应用功能
【4月更文挑战第16天】本文介绍了两个实用的Flask扩展——Flask-Login和Flask-RESTful。Flask-Login提供用户认证和会话管理,简化了登录、注销和保护路由的逻辑。而Flask-RESTful则助力构建RESTful API,支持多种HTTP方法和请求解析。通过这两个扩展,开发者能轻松增强Flask应用的功能性,实现安全的用户认证和高效的API交互。
|
3月前
|
XML JSON API
通过Flask框架创建灵活的、可扩展的Web Restful API服务
通过Flask框架创建灵活的、可扩展的Web Restful API服务
101 1