【问题标题】:How would I zip multiple StringIO files?我将如何压缩多个 StringIO 文件?
【发布时间】:2012-07-16 13:11:49
【问题描述】:

我有一个 Pyramid Web 应用程序,它使用内部 Web 服务使用 reportlab 将一些数据转换为 PDF 文件。这很好用,但一次只生成一个 PDF 文件。客户现在希望能够打印(可以压缩,而不是通过打印机实际打印)多个 PDF 文件。

我目前在底部有这段代码:

    result = {"sales_order_data": {"sales_order_list": order_pdf_data}}
    encoded_result = urllib.urlencode(result)
    received_data = requests.post('http://convert_to_pdf/sales_order', data=encoded_result)
    pdf_file = received_data.content
    content_disposition = received_data.headers['Content-Disposition']

    res = Response(content_type='application/pdf', content_disposition=content_disposition)
    res.body = pdf_file
    return res

pdf_file 是 PDF 文件的二进制形式。我正在考虑多次运行我的 pdf 转换代码,每次都将 pdf 二进制数据存储在一个列表中,然后使用 StringIO 和 ZipFile 将一堆文件压缩在一起。

我不太确定这是否可行:

list_of_pdf_files = []
for order in list_of_orders:
    <processing of data here>
    result = {"sales_order_data": {"sales_order_list": order_pdf_data}}
    encoded_result = urllib.urlencode(result)
    received_data = requests.post('http://convert_to_pdf/sales_order', data=encoded_result)
    pdf_file = received_data.content
    list_of_pdf_files.append(pdf_file)

zipped_file = <What do I do here to zip the list of pdf files?>   
content_disposition = 'attachment; filename="pdf.zip"'
res = Response(content_type='application/zip', content_disposition=content_disposition)
res.body = zipped_file
return res

在获得二进制 pdf 文件列表后,我该怎么做才能在内存中生成压缩文件并通过 content-disposition 作为响应返回该文件?

【问题讨论】:

    标签: python pyramid


    【解决方案1】:

    使用ZipFile.writestr() 将 PDF 文件一次一个写入存档。

    【讨论】:

      猜你喜欢
      • 2021-12-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-27
      • 1970-01-01
      • 2015-01-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多