Python Flask send_file StringIO 空白文件

标签 python flask stringio

我想处理 Pandas 数据帧并将其作为 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,
        download_name='a_file.txt',
        mimetype='text/csv'
    )

最佳答案

这里的问题是,在 Python 3 中,您需要将 StringIOcsv.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())
    # seeking was necessary. Python 3.5.2, Flask 0.12.2
    mem.seek(0)
    proxy.close()

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

在 Flask 2.0 之前,download_name 被称为 attachment_filename

关于Python Flask send_file StringIO 空白文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35710361/

相关文章:

javascript - 带有 Javascript 的 flask

python - 在 Flask 中为文件创建下载链接的最佳方式?

python - 如何从 pycurl 多 curl 请求中获取响应正文

printing - python 2 中打印命令后的 >> 是什么?

python - 将列表的 Python 列表转换为字符串

python 正则表达式: get end digits from a string

python - 壁虎错误 : "Equation without an equality (=) or inequality (>,<)" when calling functions within constraint and objective

javascript - 自动重新加载时增加 AJAX 和 Flask 中的变量

python - 从嵌套字典中的值构造数据框

python - 如果字符串不在一个或多个列表中则引发错误