Skip to main content
 首页 » 编程设计

python django 关闭 excel 服务器

2025年04月02日39lori

我的网站有导出excel每日报告的功能,这可能会因用户而异。由于某种原因,我不能考虑 redis 或 memcache。对于每个用户,数据库中的行数大约缺少 2-5 行。当用户调用导出到 excel 功能时,导出需要 5-10 分钟,直到该网站所有资源(ram、cpu)都用于制作该 excel,结果站点关闭 5 分钟,5 分钟后一切正常美好的。我还将查询结果分成一小部分来解决 RAM 问题,它解决了我 50% 的问题。有没有其他优化 CPU 和 RAM 的解决方案?

示例代码

def import_to_excel(request): 
    order_list = Name.objects.all() 
    book = xlwt.Workbook(encoding='utf8') 
    default_style = xlwt.Style.default_style 
    style = default_style 
    fname = 'order_data' 
    sheet = book.add_sheet(fname) 
    row = -1 
    for order in order_list: 
        row+=1 
        sheet.write(row, 1,order.first_name, style=style) 
        sheet.write(row, 2,order.last_name, style=style) 
    response = HttpResponse(mimetype='application/vnd.ms-excel') 
    response['Content-Disposition'] = 'attachment; filename=order_data_pull.xls' 
    book.save(response) 
    return response 

请您参考如下方法:

Streaming a file that takes a long time to generate you can avoid a load balancer dropping a connection that might have otherwise timed out while the server was generating the response.

  • 您还可以使用 celery 异步处理您的请求.

异步处理请求将允许您的服务器在后台工作人员处理前一个请求时接受任何其他请求。

因此您的系统将以这种方式变得更加用户友好。