Python Flask send_file StringIO空白文件 [英] Python Flask send_file StringIO blank files

查看:286
本文介绍了Python Flask send_file StringIO空白文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用python 3.5和flask 0.10.1并喜欢它,但是send_file有点麻烦.我最终要处理一个pandas数据框(来自Form数据,在本示例中未使用,但将来需要使用),并将其发送为csv格式下载(没有临时文件).我所见过的最好的实现方法是给我们StringIO.

I'm using python 3.5 and flask 0.10.1 and liking it, but having a bit of trouble with send_file. I ultimately want to process a pandas dataframe (from Form data, which is unused in this example but necessary in the future) and send it to download as a csv (without a temp file). The best way to accomplish this I've seen is to us StringIO.

这是我尝试使用的代码:

Here is the code I'm attempting to use:

@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')

以正确的名称下载文件,但是该文件完全空白.

A file downloads with the proper name, however the file is completely blank.

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

Any ideas? Issues with encoding? Has this been answered elsewhere? Thanks!

推荐答案

这里的问题是,在Python 3中,您需要将StringIOcsv.write一起使用,而send_file需要BytesIO,因此您必须两者.

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('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'
    )

这篇关于Python Flask send_file StringIO空白文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆