python flask restful入门_flask-restful 快速入门

快速入门

资源丰富的路由

多种类型的返回值

多URL访问同一个资源

完整案例

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

快速入门

api.py

from flask importFlaskfrom flask.ext importrestful

app= Flask(__name__)

api=restful.Api(app)classHelloWorld(restful.Resource):defget(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 importFlask, requestfrom flask.ext.restful importResource, Api

app= Flask(__name__)

api=Api(app)

todos={}classTodoSimple(Resource):defget(self, todo_id):return{todo_id: todos[todo_id]}defput(self, todo_id):

todos[todo_id]= request.form['data']return{todo_id: todos[todo_id]}

api.add_resource(TodoSimple,'/')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/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"

}

心得

-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/todo1 -d'data=jimi' -X PUT

{

"todo1":"jimi"

}

jihite@ubuntu:~$ curl http://127.0.0.1:5000/todo1 -X GET

{

"todo1":"jimi"

}

jihite@ubuntu:~$ curl http://127.0.0.1:5000/todo1 -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 importFlask, requestfrom flask.ext.restful importResource, Api

app= Flask(__name__)

api=Api(app)

todos={}classTodo1(Resource):defget(self):return {'task': 'apple'}classTodo2(Resource):defget(self):return {'task': 'babana'}, 201

classTodo3(Resource):defget(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/Todo1

{

"task":"apple"

}

jihite@ubuntu:~/project/flask$ curl http://127.0.0.1:5000/Todo2

{

"task":"babana"

}

jihite@ubuntu:~/project/flask$ curl http://127.0.0.1:5000/Todo3

{

"task":"pear"

}

jihite@ubuntu:~/project/flask$ curl http://127.0.0.1:5000/Todo4

404 Not Found

Not Found

The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.

心得

api.add_resource通过第二个参数关联第一个参数指定的类

多URL访问同一个资源

api_points.py

from flask importFlaskfrom flask.ext importrestful

app= Flask(__name__)

api=restful.Api(app)classHelloWorld(restful.Resource):defget(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 importFlaskfrom flask.ext.restful importreqparse, abort, Api, Resource

app= Flask(__name__)

api=Api(app)

TODOS={'todo1': {'task': 'build an API'},'todo2': {'task': '?????'},'todo3': {'task': 'profit!'},

}defabort_if_todo_doesnt_exist(todo_id):if todo_id not inTODOS:

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

classTodo(Resource):defget(self, todo_id):

abort_if_todo_doesnt_exist(todo_id)returnTODOS[todo_id]defdelete(self, todo_id):

abort_if_todo_doesnt_exist(todo_id)delTODOS[todo_id]return '', 204

defput(self, todo_id):

args=parser.parse_args()

task= {'task': args['task']}

TODOS[todo_id]=taskreturn task, 201

#TodoList#shows a list of all todos, and lets you POST to add new tasks

classTodoList(Resource):defget(self):returnTODOSdefpost(self):

args=parser.parse_args()

todo_id= int(max(TODOS.keys()).lstrip('todo')) + 1todo_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/')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/todo2

{

"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

* Trying127.0.0.1...

* Connected to127.0.0.1 (127.0.0.1) port5000 (#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: */*

>

* HTTP1.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 Jul2015 06:29:37 GMT

<

* Closing connection0

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/todo3 -d'task=misi' -X PUT -v

* Hostname was NOT found in DNS cache

* Trying127.0.0.1...

* Connected to127.0.0.1 (127.0.0.1) port5000 (#0)

> PUT /todos/todo3 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 of9 bytes

* HTTP1.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 Jul2015 06:30:24 GMT

<

{

"task":"misi"

}

* Closing connection0

jihite@ubuntu:~/project/flask$ curl http://127.0.0.1:5000/4

{

"todo1": {

"task":"build an API"

},

"todo3": {

"task":"misi"

},

"todo4": {

"task":"hello"

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值