【Python@flask】flask_restful (一)
2020-03-07 本文已影响0人
seelingzheng
关注公众号"seeling_GIS",回复『前端视频』,领取前端学习视频资料
开发环境
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
引入 flask 、flask_restful
from flask import Flask
from flask_restful import Resource,Api
初始化 Api
app = Flask(__name__)
api = Api(app)
创建路由
class HelloWorld(Resource):
def get(self):
return{}
api.add_resource(HelloWorld,'/')
通过第三方工具调用查看或者通过命令行调用
![](https://img.haomeiwen.com/i5310582/922cc232d40bcdc4.png)
![](https://img.haomeiwen.com/i5310582/d4f5b518704e2777.png)
通过参数查询和新增数据
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 参数中添加同名参数
![](https://img.haomeiwen.com/i5310582/d8f5216b87544597.png)
![](https://img.haomeiwen.com/i5310582/439604bf095583de.png)
![](https://img.haomeiwen.com/i5310582/627baa407c88b452.png)
格式化输出
# 引入 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')
![](https://img.haomeiwen.com/i5310582/90b8d57d911300a3.png)
![](https://img.haomeiwen.com/i5310582/f19b4bc41375d8f2.png)
参考:https://flask-restful.readthedocs.io/en/latest/
参数类型:http://www.pythondoc.com/Flask-RESTful/extending.html#id6