【问题标题】:How to use sqlalchemy core for pagination in Flask?如何在 Flask 中使用 sqlalchemy 核心进行分页?
【发布时间】:2017-01-13 11:21:21
【问题描述】:

我只使用带有 SQLAlchemy 核心 的烧瓶框架。我从“选择”语句返回的结果集包含数千条记录。我想使用分页来避免内存错误。对于任何页面,如何动态地使用 api GET 方法的光标获取 JSON 输出?我在这里How to use cursor() for pagination? 尝试了接受的解决方案,但不能完全正确。请指导。使用 PostgreSQL 9.4 我尝试过的选项:

1.

@app.route('/test/api/v1.0/docs_page/<int:page>', methods=['POST'])
def search_docs_page(page):
    if 'id' in session:
        doc_list = []
        no_of_pgs = 0
        doc_list = common_search_code()
        # doc_list is a resultset after querying the table for a set of query condition  
        header_dict = dict(request.headers)
        for i in header_dict.items():
            if i == 'Max-Per-Page':
                max_per_pg = int(header_dict[i])
        no_of_pgs = len(doc_list) / max_per_pg
        print 'number of doc: ' + str(len(doc_list))
        print 'number of pages: ' +  str(no_of_pgs)
        print 'max per page:' + str(max_per_pg)
        print 'page number: '+ str(page)
        page = int(request.args.get(page, type=int, default=1))
        pagination = Pagination(page=page,
                                total=len(doc_list),
                                search=True, record_name='documents')

        return jsonify({'pagination': list(pagination.__dict__),
                        'doc_list': doc_list}), 200

    return jsonify({'message': "Unauthorized"}), 401

我想通过在请求标头中传递参数来控制每页要打印的记录数,就像在这个 curl 中一样:

curl -b cookies.txt -X POST http://localhost:8081/test/api/v1.0/docs_page/1 -H 'max_per_page:4' -H 'Content-type:application/json'

@app.route('/test/api/v1.0/docs_page2', methods=['POST'])
 def search_docs_page2():
     if 'id' in session:
         docs = []
         no_of_pgs = 0
         doc_list = common_search_code()
         header_dict = dict(request.headers)
         for i in header_dict.items():
             if i == 'Max-Per-Page':
                 max_per_pg = int(header_dict[i])
         no_of_pgs = len(doc_list) / max_per_pg
         print 'number of doc: ' + str(len(doc_list))
         print 'number of pages: ' +  str(no_of_pgs)
         print 'max per page:' + str(max_per_pg)
         page = int(request.form.get('page', type=int, default=1))
         cursor = request.form.get('cursor')
         if cursor:
             print 'hey'
             doc_list.with_cursor(cursor)
             docs = doc_list.fetchmany(4)
             for r in docs:
                 print r, 'rrrr'

         return jsonify({'docs': docs}), 200

     return jsonify({'message': "Unauthorized"}), 401







curl:curl -b cookies.txt  -X POST http://localhost:8081/test/api/v1.0/docs_page2 -H 'max_per_page:4' -H 'Content-type:application/json' -F 'cursor=1'

【问题讨论】:

  • 如果你发布你已经尝试过的东西会更好......
  • dict(header_dict.items()) 是不必要的。它从字典创建一个新字典。只需遍历header_dict。如果您只关心一个键,请检查该键而不是遍历所有键。 max_per_pg = header_dict['Max-Per-Page'].
  • common_search_code 是否返回光标?你是如何查询数据库的?您使用的是engine.execute 还是表格对象?此外,您链接到的问题是关于 Google App Engine 的,不适用于 SQLAlchemy。
  • common_search_code 在应用搜索条件后返回文档列表。我使用了 rs = conn.execute(s),然后根据某些条件创建了此处返回的文档列表。

标签: python pagination sqlalchemy


【解决方案1】:

目前,我已对上述代码进行了更改以使其以这种方式工作:

@app.route('/test/api/v1.0/docs_page2', methods=['POST'])
def search_docs_page2():
    if 'id' in session:
        docs = []
        no_of_pgs = 0
        header_dict = dict(request.headers)
        for k in header_dict:
            print header_dict[k], 'key', k
        if 'Max-Per-Page' in header_dict.keys():
            max_per_pg = int(header_dict['Max-Per-Page'])
            page_no = int(request.headers.get('page_no', type=int, default=1))
            offset1 = (page_no - 1) * max_per_pg
            query1 = common_search_code()
            s = query1.limit(max_per_pg).offset(offset1)
            rs = conn.execute(s)
            for r in rs:
                docs.append(dict(r))
            # no_of_pgs = float(len(doc_list) / float(max_per_pg))
            no_of_pgs = float(len(docs) / float(max_per_pg))
            no_of_pgs = int(math.ceil(no_of_pgs))
            print 'number of doc: ' + str(len(docs))
            print 'number of pages: ' +  str(no_of_pgs)
            print 'max per page:' + str(max_per_pg)
            # docs.append(doc_list[offset:(offset + max_per_pg)])
            return jsonify({'docs': docs,
                            'no_of_pages': str(no_of_pgs)}), 200

        return jsonify({'message': "Max. per page not specified"}), 400

    return jsonify({'message': "Unauthorized"}), 401

相同的卷曲:

curl -b cookies.txt  -X POST http://localhost:8081/test/api/v1.0/docs_page2 -H 'max_per_page:4' -H 'Content-type:application/json' -H 'page_no:2'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-05
    • 2021-02-10
    • 1970-01-01
    • 2016-07-13
    • 2023-03-20
    • 2017-08-23
    • 2014-10-09
    相关资源
    最近更新 更多