1. 构建基本的RESTful API
创建一个api,在内容中存放和获取提交的task数据。
from flask import Flask, abort, request, jsonify
app = Flask(__name__)
tasks = []
@app.route('/add/', methods=['POST'])
def add_task():
if not request.json:
abort(400)
task = {
'id': request.json['id'],
'description': request.json['description']
}
task_old = list(filter(lambda t: t['id'] == int(task.id), tasks))
if len(task_old) > 0:
return jsonify({'result': 'task already exist'})
else:
tasks.append(task)
return jsonify({'result': 'add successfully'})
@app.route('/get/', methods=['GET'])
def get_task():
if not request.args or 'id' not in request.args:
# 没有指定id则返回全部
return jsonify(tasks)
else:
task_id = request.args['id']
task = list(filter(lambda t: t['id'] == int(task_id), tasks))
return jsonify(task[0]) if len(task)>0 else jsonify({'result': 'not found'})
if __name__ == '__main__':
app.run(debug=True)
执行add请求发送数据
在Postman中执行get请求
2. 用扩展库flask-restful
安装flask-restful
pip install flask-restful
from flask import Flask
from flask_restful import reqparse, Api, Resource, request
app = Flask(__name__)
api = Api(app)
parser = reqparse.RequestParser()
tasks = []
class Task(Resource):
def get(self):
return tasks
def post(self):
# 如果请求类型是json,用request.json
# 如果请求类型是x-www-form-urlencoded,用request.form
task = request.json
task_old = list(filter(lambda t: t['id'] == int(task.id), tasks))
if len(task_old) > 0:
return {'result': 'task already exist'}
else:
tasks.append(task)
return {'result': 'add successfully'}
# 设置路由
api.add_resource(Task, '/tasks/')
if __name__ == '__main__':
app.run(debug=True)
Post提交数据
Get请求数据