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

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

问题描述

我正在使用 python 3.5 和 Flask 0.10.1 并且喜欢它,但是在使用 send_file 时遇到了一些麻烦.我最终想处理一个 Pandas 数据帧(来自表单数据,在本例中未使用,但将来需要)并将其作为 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.writesend_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())
    # 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天全站免登陆