Python Flask send_file StringIO空白文件

Dan*_*ock 19 python stringio flask

我正在使用python 3.5和flask 0.10.1并且喜欢它,但是在send_file上遇到了一些麻烦.我最终想要处理一个pandas数据帧(来自Form数据,在本例中未使用但将来是必需的)并将其作为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,\
    attachment_filename = 'a_file.txt', mimetype = 'text/csv')
Run Code Online (Sandbox Code Playgroud)

使用正确的名称下载文件,但文件完全空白.

有任何想法吗?编码问题?有没有在其他地方回答过?谢谢!

Rad*_*adu 27

这里的问题是在Python 3中你需要使用StringIOwith csv.writesend_filerequire BytesIO,所以你必须同时执行这两个操作.

@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('utf-8'))
    # seeking was necessary. Python 3.5.2, Flask 0.12.2
    mem.seek(0)
    proxy.close()

    return send_file(
        mem,
        as_attachment=True,
        attachment_filename='test.csv',
        mimetype='text/csv'
    )
Run Code Online (Sandbox Code Playgroud)


lor*_*. j 13

我想你应该写字节.

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'jJust 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,
                     attachment_filename='a_file.txt',
                     mimetype='text/csv')


if __name__ == '__main__':
    app.run(debug=True)
Run Code Online (Sandbox Code Playgroud)