【问题标题】:Iterate over list of dictionaries efficiently in pagination在分页中有效地迭代字典列表
【发布时间】:2019-03-31 15:47:51
【问题描述】:

Flask 分页支持直接在 DB 对象上进行分页,而我需要有效地分页和呈现大量记录列表。

def modify(records):
    for rec in records:
        _rec = to_dict(rec, keys=['required', 'keys', 'only']) 
        _rec.update({'cal_vals': calculated_Vals(rec))
        yield _rec   

@app.route('/display/<type>/' methods=['POST'])
def render_records(typ):
    page = request.args.get('page', 1, type=int)
    records = db.objects.find(type=typ) #Huge list 30K to 40K records
    records = modify(records) 
    # This wont work as it takes out the count from db.objects.all()  
    records = records.paginate(page, per_page=200, False)
    return render_template(
    'show_records.html',
     response ={'records': records, 'context_vars':other_vals()},

还有哪些其他方法可以实现这一目标?

【问题讨论】:

  • 请更清楚地解释您的问题。您真的遇到性能问题吗? 40000 条记录并不多,几乎任何数据库都可以轻松处理。
  • 请更新您的问题以说明您正在使用哪个数据库以及您用于访问它的数据库库。这些都是重要的细节。
  • 记录是什么样子的,它们是如何排序的,typ 实际做了什么也会有所帮助。另外,为什么您认为将结果分成页面是个好主意?修改有什么作用?
  • @Soviut 你能回答这个吗:stackoverflow.com/questions/59543343/….

标签: python flask pagination jinja2


【解决方案1】:

我不得不做出很多假设,因为您的问题缺少很多关于正在使用的数据库和数据库库的详细信息。

数据库处理 40,000 条记录应该没有问题。您的性能问题可能与您在每条记录上运行 modify() 函数有关,这迫使数据库库一次“物化”内存中的每条记录。只有这样,您才能运行分页,此时您丢弃了 99% 的结果您花了很多时间修改它们。

解决方案是仅在分页结果上运行您的函数。

records = db.objects.find(type=typ)
paginated_records = records.paginate(page, per_page=200, False)
modified_records = modify(paginated_records) # this only runs on 200 records

【讨论】:

    猜你喜欢
    • 2015-07-07
    • 1970-01-01
    • 1970-01-01
    • 2015-07-04
    • 2012-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多