Python Flask send_file StringIO 空白文件

新手上路,请多包涵

我想处理 Pandas 数据帧并将其作为 CSV 文件发送下载,无需临时文件。我见过的实现此目的的最佳方法是使用 StringIO 。使用下面的代码,将下载一个具有正确名称的文件,但是该文件是完全空白的,并且没有显示任何错误。为什么文件不包含数据?

 @app.route('/test_download', methods = ['POST'])
def test_download():
    buffer = StringIO()
    buffer.write('Just some letters.')
    buffer.seek(0)
    return send_file(
        buffer,
        as_attachment=True,
        download_name='a_file.txt',
        mimetype='text/csv'
    )

原文由 Daniel Hitchcock 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 961
2 个回答

The issue here is that in Python 3 you need to use StringIO with csv.write and send_file requires BytesIO , so you have to do both .

 @app.route('/test_download')
def test_download():
    row = ['hello', 'world']
    proxy = io.StringIO()

    writer = csv.writer(proxy)
    writer.writerow(row)

    # Creating the byteIO object from the StringIO Object
    mem = io.BytesIO()
    mem.write(proxy.getvalue().encode())
    # seeking was necessary. Python 3.5.2, Flask 0.12.2
    mem.seek(0)
    proxy.close()

    return send_file(
        mem,
        as_attachment=True,
        download_name='test.csv',
        mimetype='text/csv'
    )

在 Flask 2.0 之前, download_name 被称为 attachment_filename

原文由 Radu 发布,翻译遵循 CC BY-SA 4.0 许可协议

使用 BytesIO 写入字节。

 from io import BytesIO
from flask import Flask, send_file

app = Flask(__name__)

@app.route('/test_download', methods=['POST'])
def test_download():
    # Use BytesIO instead of StringIO here.
    buffer = BytesIO()
    buffer.write(b'Just some letters.')
    # Or you can encode it to bytes.
    # buffer.write('Just some letters.'.encode('utf-8'))
    buffer.seek(0)
    return send_file(
        buffer,
        as_attachment=True,
        download_name='a_file.txt',
        mimetype='text/csv'
    )

在 Flask 2.0 之前, download_name 被称为 attachment_filename

原文由 lord63. j 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏