其他分享
首页 > 其他分享> > 优化 web service 接口

优化 web service 接口

作者:互联网

目前 API 的设计的问题就是迫使客户端在任务标识返回后去构造 URIs。这对于服务器是十分简单的,但是间接地迫使客户端知道这些 URIs 是如何构造的,这将会阻碍我们以后变更这些 URIs。

不直接返回任务的 ids,我们直接返回控制这些任务的完整的 URI,以便客户端可以随时使用这些 URIs。为此,我们可以写一个小的辅助函数生成一个 “公共” 版本任务发送到客户端:

from flask import url_for

def make_public_task(task):
    new_task = {}
    for field in task:
        if field == 'id':
            new_task['uri'] = url_for('get_task', task_id=task['id'], _external=True)
        else:
            new_task[field] = task[field]
    return new_task

这里所有做的事情就是从我们数据库中取出任务并且创建一个新的任务,这个任务的 id 字段被替换成通过 Flask 的 url_for 生成的 uri 字段。

当我们返回所有的任务列表的时候,在发送到客户端之前通过这个函数进行处理:

@app.route('/todo/api/v1.0/tasks', methods=['GET'])
def get_tasks():
    return jsonify({'tasks': map(make_public_task, tasks)})

这里就是客户端获取任务列表的时候得到的数据:

$ curl -i http://localhost:5000/todo/api/v1.0/tasks
HTTP/1.0 200 OK
Content-Type: application/json
Content-Length: 406
Server: Werkzeug/0.8.3 Python/2.7.3
Date: Mon, 20 May 2013 18:16:28 GMT

{
  "tasks": [
    {
      "title": "Buy groceries",
      "done": false,
      "description": "Milk, Cheese, Pizza, Fruit, Tylenol",
      "uri": "http://localhost:5000/todo/api/v1.0/tasks/1"
    },
    {
      "title": "Learn Python",
      "done": false,
      "description": "Need to find a good Python tutorial on the web",
      "uri": "http://localhost:5000/todo/api/v1.0/tasks/2"
    }
  ]
}

标签:web,tasks,service,接口,v1.0,任务,task,URIs,客户端
来源: https://blog.csdn.net/qq_42370150/article/details/91379390