1

我正在尝试通过我的服务器上的 StreamingResponse(因此它不会保存在本地)创建一个 Zip 文件以发送到前端。Zip 文件将包含从多个数据帧转换而来的 CSV 文件。到目前为止,我正在通过 Postman 获取 Zip 文件,但是当我尝试打开它时,我收到一条错误消息,表明 Zip 文件已损坏: 错误

到目前为止我写的代码:

def prepare_zip(dafaframes):

outfile = io.BytesIO()
with zipfile.ZipFile(outfile, 'w') as zf:
    for n, f in enumerate(dafaframes):
        stream = io.StringIO()
        f.to_csv(stream, index=False)
        stream.seek(0)
        csv_buffer = stream.read()
        zf.writestr("{}.csv".format(n), csv_buffer)
    # Returns a csv prepared to be downloaded in the FrontEnd
    outfile.seek(0)
    response = StreamingResponse(outfile,
                                 media_type="application/x-zip-compressed"
                                 )

    response.headers["Content-Disposition"] = "attachment; filename=test.zip"

    return response

'dataframes' 参数是一个列表,其中包含应该转换为 CSV 并由 Zip 文件保存的数据帧。

4

0 回答 0