flask_restful
webgis 2020-02-02
python
flask
# 开发环境
conda:4.8.2 #通过 anaconda 安装
python:3.6
flask:1.1.1 # 1. conda install flask; 2. pip install flask
flask_restful:0.3.8 # pip install flask_restful
1
2
3
4
5
6
7
2
3
4
5
6
7
# 引入 flask 、flask_restful
from flask import Flask
from flask_restful import Resource,Api
1
2
2
# 初始化 Api
app = Flask(__name__)
api = Api(app)
1
2
2
# 创建路由
class HelloWorld(Resource):
def get(self):
return{}
api.add_resource(HelloWorld,'/')
1
2
3
4
2
3
4
# 通过第三方工具调用查看或者通过命令行调用

# 通过参数查询和 新增数据
values = {}
class AddValue(Resource):
def get(self,id):
return {id:values.get(id)}
def post(self,id):
try:
values[id] = json.loads(request.data.decode())
return {id : values[id]}
except:
return '数据格式错误'
def put(self,id):
try:
values[id] = json.loads(request.data.decode())
return {id : values[id]}
except:
return '数据格式错误'
def delete(self,id):
del values[id]
return '删除成功:'+ str(id)
api.add_resource(AddValue,'/<int:id>')
#参数设置 <int:id>
# int:限制参数数据类型
# id: 参数名称, 需要在 get put 参数中添加同名参数
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
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

# 格式化输出
# 引入 fields,marshal_with
from flask_restful import fields,marshal_with,abort,reqparse
#构建返回数据的格式
todo_field={
'id':fields.Integer(),
'title':fields.String(default=''),
'content':fields.String(default='')
}
class TODO(object):
def __init__(self, id, title, content):
self.id = id
self.title = title
self.content = content
class TodoList(Resource):
@marshal_with(todo_field) #,envelope='resource' envelope用户对返回的数据进行封装
def get(self, id = None):
todolist =list(filter(lambda t: t.id == id, TodoLists))
if len(todolist) ==0:
abort(400)
else:
val = todolist[0]
return val
#@marshal_with(todo_field)
def post(self):
parse = reqparse.RequestParser() # 格式化传入的数据
parse.add_argument('id',trim=True, type=int, help='todolist id')
parse.add_argument('title',type=str )
parse.add_argument('content',type=str )
args = parse.parse_args()
id = int(args.get('id'))
#查询数据列表
todo = list(filter(lambda t: t.id == id, TodoLists))
if len(todo) == 0:
todo = TODO(id, title=args.get('title'), content=args.get('content'))
TodoLists.append(todo)
return jsonify({
"msg":"添加成功"
})
else:
print({"msg":'资源已存在'})
return jsonify({"msg":'资源已存在'}), 403
api.add_resource (TodoList, '/todo/', '/todo/<int:id>/',endpoint='todo')
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
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

参考:https://flask-restful.readthedocs.io/en/latest/
参数类型:http://www.pythondoc.com/Flask-RESTful/extending.html#id6