烧瓶静息分页 [英] Flask restful pagination

查看:45
本文介绍了烧瓶静息分页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在很短的期限内完成一个非常简单的API.烧瓶躁动似乎很理想,除了以下几点:在分页文档中找不到任何内容.给定一个简单的端点,如下所示:

从烧瓶导入烧瓶中的

 ,请求从flask_restful导入资源,Api从sqlalchemy导入create_engine导入jsonapp = Flask(__ name__)api = Api(应用程式)员工类别(资源):def get():返回json.dumps([[{''employees':'hello world'} for range in(1000)])api.add_resource(员工,'/员工')如果__name__ =='__main__':app.run(端口='5002') 

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

解决方案

您可以使用:

  • flask_sqlalchemy 提供的分页

    脚注:

    • 可以使用参数或不使用参数来调用API.有效的API调用示例:
      • http://127.0.0.1:5002/员工
      • 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
    • 开始的默认值为1, limit 的默认值为20.
    • 如果 start 值大于数据长度或限制为负,则API将返回HTTP 404错误并显示错误消息:

    I need to throw together an very simple API with a short deadline. Flask-restful seems ideal except for one thing: I can't find anything in the documentation about pagination. Given a simple endpoint like this:

    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')
    

    Is there any way for flask_restful to paginate the endpoint so that I only receive, say, 100 of those dictionaries per page, and have URLs for 'next' and 'previous'? If not, is it maybe possible to create pagination some other way in Flask? Thanks.

    解决方案

    You can either use:

    As I am not sure if you are using flask_sqlalchemy or any model information, I am showing the custom pagination technique.

    I have modified the data to show the employee id. And I also used jsonify from Flask.

    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)
    

    Output:

    Footnote:

    • API can be called with parameter or without parameter. Example of valid API calls:
      • 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
    • Default value for start is 1 and limit is 20.
    • If the start value is greater than data length or limit is negative then the API will return HTTP 404 error with an error message:

    这篇关于烧瓶静息分页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆