小编典典

Python Flask send_file 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')

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

有任何想法吗?编码有问题吗?这在别的地方有答案吗?谢谢!


阅读 995

收藏
2020-04-07

共1个答案

小编典典

这里的问题是,在Python 3中,你需要使用StringIO和,csv.write并且send_file必须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'
    )
2020-04-07