基于Flask的 api(二)

基于Flask的 api(二)

使用flask 构造服务的方法有:

  (1)利用路由实现

  (2)利用flask的扩展插件实现

利用路由实现REST API

1.GET

获取资源

获取列表

from flask import Flask,request,abort,jsonify
app = Flask(__name__)

tasks = [
    {
        'id': 1,
        'title': u'Buy groceries',
        'description': u'Milk, Cheese, Pizza, Fruit, Tylenol',
        'done': False
    },
    {
        'id': 2,
        'title': u'Learn Python',
        'description': u'Need to find a good Python tutorial on the web',
        'done': False
    }]

    @app.route("/tasks", methods=['GET'])
    def get_tasks():
      return jsonify({'tasks': tasks})

    if __name__ == "__main__":
        app.run(debug=True)

测试

$ curl -i http://localhost:5000/tasks
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed100   218  100   218    0     0    931      0 --:--:-- --:--:-- --:--:--   931HTTP/1.0 200 OKContent-Type: application/jsonContent-Length: 218Server: Werkzeug/1.0.1 Python/3.6.0Date: Mon, 23 Nov 2020 13:45:24 GMT

{"tasks":[{"description":"Milk, Cheese, Pizza, Fruit, Tylenol","done":false,"id":1,"title":"Buy groceries"},{"description":"Need to find a good Python tutorial on the web","done":false,"id":2,"title":"Learn Python"}]}

获取其中一个

from flask import Flask,
request,abort,jsonify
app = Flask(__name__)
tasks = [
    {
        'id': 1,
        'title': u'Buy groceries',
        'description': u'Milk, Cheese, Pizza, Fruit, Tylenol',
        'done': False
    },
    {
        'id': 2,
        'title': u'Learn Python',
        'description': u'Need to find a good Python tutorial on the web',
        'done': False
    }]

    @app.route("/tasks/<int:task_id>", methods=['GET'])

    def get_task(task_id):
      task = list(filter(lambda t: t['id'] == task_id, tasks))
    if len(task) == 0:
        abort(404)
    return jsonify({'task': task[0]})

    if __name__ == "__main__":
       app.run(debug=True)

测试

$ curl -i http://localhost:5000/tasks/1
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed100   142  100   142    0     0    606      0 --:--:-- --:--:-- --:--:--   606HTTP/1.0 200 OKContent-Type: application/jsonContent-Length: 142Server: Werkzeug/1.0.1 Python/3.6.0Date: Mon, 23 Nov 2020 14:31:42 GMT

{
  "task": {
    "description": "Milk, Cheese, Pizza, Fruit, Tylenol",
    "done": false,
    "id": 1,
    "title": "Buy groceries"
  }}

2.POST

创建资源

from flask import Flask,request,abort,jsonify
app = Flask(__name__)
tasks = [
    {
        'id': 1,
        'title': u'Buy groceries',
        'description': u'Milk, Cheese, Pizza, Fruit, Tylenol',
        'done': False
    },
    {
        'id': 2,
        'title': u'Learn Python',
        'description': u'Need to find a good Python tutorial on the web',
        'done': False
    }]

    @app.route('/tasks', methods=['POST'])
    def create_task():
     if not request.json or not 'title' in request.json:
        abort(400)
    task = {
        'id': tasks[-1]['id'] + 1,
        'title': request.json['title'],
        'description': request.json.get('description', ""),
        'done': False
    }
    tasks.append(task)

    return jsonify({'newTask': task,'list':tasks})

    if __name__ == "__main__":
    app.run(debug=True)

测试

$ curl -i -H "Content-Type: application/json" -X POST -d '{"title":"ABC"}' http://localhost:5000/tasks
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed100   528  100   513  100    15   2192     64 --:--:-- --:--:-- --:--:--  2256HTTP/1.0 201 CREATEDContent-Type: application/jsonContent-Length: 513Server: Werkzeug/1.0.1 Python/3.6.0Date: Mon, 23 Nov 2020 14:38:50 GMT

 {
  "list": [
    {
      "description": "Milk, Cheese, Pizza, Fruit, Tylenol",
      "done": false,
      "id": 1,
      "title": "Buy groceries"
    },
    {
      "description": "Need to find a good Python tutorial on the web",
      "done": false,
      "id": 2,
      "title": "Learn Python"
    },
    {
      "description": "",
      "done": false,
      "id": 3,
      "title": "ABC"
    }
  ],
  "newTask": {
    "description": "",
    "done": false,
    "id": 3,
    "title": "ABC"
  }}

3.PUT

更新资源

from flask import Flask,request,abort,jsonify
app = Flask(__name__)
tasks = [
    {
        'id': 1,
        'title': u'Buy groceries',
        'description': u'Milk, Cheese, Pizza, Fruit, Tylenol',
        'done': False
    },
    {
        'id': 2,
        'title': u'Learn Python',
        'description': u'Need to find a good Python tutorial on the web',
        'done': False
    }]
    @app.route('/tasks/<int:task_id>', methods=['PUT'])

    def update_task(task_id):
      task = list(filter(lambda t:t['id']==task_id,tasks))
    if len(task)==0:
        abort(404)
    if not request.json:
        abort(400)
    if 'title' in request.json and not isinstance(request.json['title'],str):
        abort(400)
    if 'description' in request.json and not isinstance(request.json['description'],str):
        abort(400)
    if 'done' in request.json and not isinstance(request.json['done'],bool):
        abort(400)
    task[0]['title'] = request.json.get('title',task[0]['title'])
    task[0]['description'] = request.json.get('description', task[0]['description'])
    task[0]['done'] = request.json.get('done', task[0]['done'])
    return jsonify({'task':task[0]})
    if __name__ == "__main__":
       app.run(debug=True)

测试

$ curl -i -H "Content-Type: application/json" -X PUT -d '{"title":"ABC"}' http://localhost:5000/tasks/1
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed100   147  100   132  100    15    564     64 --:--:-- --:--:-- --:--:--   628HTTP/1.0 200 OKContent-Type: application/jsonContent-Length: 132Server: Werkzeug/1.0.1 Python/3.6.0Date: Mon, 23 Nov 2020 15:00:31 GMT
 {
  "task": {
    "description": "Milk, Cheese, Pizza, Fruit, Tylenol",
    "done": false,
    "id": 1,
    "title": "ABC"
  }}

4.DELETE

删除资源

from flask import Flask,request,abort,jsonify
app = Flask(__name__)
tasks = [
    {
        'id': 1,
        'title': u'Buy groceries',
        'description': u'Milk, Cheese, Pizza, Fruit, Tylenol',
        'done': False
    },
    {
        'id': 2,
        'title': u'Learn Python',
        'description': u'Need to find a good Python tutorial on the web',
        'done': False
    }]

    @app.route('/tasks/<int:task_id>',methods=['DELETE'])
    def delete_task(task_id):
    task = list(filter(lambda t: t['id']==task_id,tasks))
    if len(task) ==0:
        abort(404)
    tasks.remove(task[0])
    return jsonify({'result': True,'list':tasks})

    if __name__ == "__main__":
     app.run(debug=True)

测试

$ curl -i -H "Content-Type: application/json" -X DELETE http://localhost:5000/tasks/1
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed100   191  100   191    0     0    812      0 --:--:-- --:--:-- --:--:--   812HTTP/1.0 200 OKContent-Type: application/jsonContent-Length: 191Server: Werkzeug/1.0.1 Python/3.6.0Date: Mon, 23 Nov 2020 15:02:52 GMT
 {
  "list": [
    {
      "description": "Need to find a good Python tutorial on the web",
      "done": false,
      "id": 2,
      "title": "Learn Python"
    }
  ],
  "result": true}
(0)

相关推荐