烧瓶静息分页

时间:2019-04-05 20:36:36

标签: python flask flask-restful

我需要在很短的期限内完成一个非常简单的API。烧瓶安宁似乎很理想,除了以下几点:我在分页文档中找不到任何内容。给定一个简单的端点,像这样:

from flask import Flask, request 
from flask_restful import Resource, Api 
from sqlalchemy import create_engine
import json 

app = Flask(__name__)
api = Api(app)

class Employees(Resource):
    def get(self):
        return json.dumps([{'employees': 'hello world'} for i in range(1000)])

api.add_resource(Employees, '/employees')

if __name__ == '__main__':
    app.run(port='5002')

是否有办法让flask_restful对端点进行分页,以便每页仅接收100个这样的字典,并具有“下一个”和“上一个”的URL?如果不是,是否有可能在Flask中以其他方式创建分页?谢谢。

1 个答案:

答案 0 :(得分:3)

您可以使用:

由于我不确定您是否使用flask_sqlalchemy或任何型号信息,因此我在显示自定义分页技术。

我已修改数据以显示员工ID。而且我还使用了Flask的jsonify

from flask import Flask, request, jsonify, abort
from flask_restful import Resource, Api 


app = Flask(__name__)
api = Api(app)

data = [{'employee_id': i+1} for i in range(1000)]

def get_paginated_list(results, url, start, limit):
    start = int(start)
    limit = int(limit)
    count = len(results)
    if count < start or limit < 0:
        abort(404)
    # make response
    obj = {}
    obj['start'] = start
    obj['limit'] = limit
    obj['count'] = count
    # make URLs
    # make previous url
    if start == 1:
        obj['previous'] = ''
    else:
        start_copy = max(1, start - limit)
        limit_copy = start - 1
        obj['previous'] = url + '?start=%d&limit=%d' % (start_copy, limit_copy)
    # make next url
    if start + limit > count:
        obj['next'] = ''
    else:
        start_copy = start + limit
        obj['next'] = url + '?start=%d&limit=%d' % (start_copy, limit)
    # finally extract result according to bounds
    obj['results'] = results[(start - 1):(start - 1 + limit)]
    return obj

class Employees(Resource):
    def get(self):
        return jsonify(get_paginated_list(
        data, 
        '/employees', 
        start=request.args.get('start', 1), 
        limit=request.args.get('limit', 20)
    ))

api.add_resource(Employees, '/employees')

if __name__ == '__main__':
    app.run(port='5002', debug=True)

输出:

paginated output

脚注:

  • 可以使用参数或不使用参数来调用API。有效的API调用示例:
    • http://127.0.0.1:5002/employees
    • http://127.0.0.1:5002/employees?start=41&limit=20
    • http://127.0.0.1:5002/employees?limit=5
    • http://127.0.0.1:5002/employees?start=100
  • start的默认值为1,而limit的默认值为20。
  • 如果start值大于数据长度或限制为负,则API将返回HTTP 404错误并显示错误消息:

HTTP 404 error