Python Flask send_file StringIO空白文件

时间:2016-02-29 21:48:13

标签: python flask stringio

我使用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')

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

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

3 个答案:

答案 0 :(得分:22)

这里的问题是,在Python 3中,您需要StringIO使用csv.writesend_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(0)

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

答案 1 :(得分:10)

我猜你应该写字节。

$('[id="image-value"]').change(function(e) {
var file_data = $(this).prop('files')[0];   
var form_data = new FormData();

form_data.append('file', file_data);

$.ajax({ // 02102016 AA: picture_caption
url: 'controllerName/upload_picture/', //add the controller.
dataType: 'json',
cache: false,
contentType: false,
processData: false,
data: form_data,                         
type: 'post',
success: function(data){
    alert(data);
},
error: function(jqXHR, textStatus, errorThrown) {
    console.error("The following error occured: " + textStatus, errorThrown);
}

答案 2 :(得分:0)

如果有人在Flask上使用python 2.7并通过导入它来获取有关模块StringIO的错误。这篇文章可以帮助您解决问题。

如果要导入String IO模块,则只需使用以下命令更改导入语法:来自io import StringIO ,而不是来自StringIO import StringIO

如果您正在使用图片或其他一些资源,您也可以使用来自io import BytesIO

谢谢