我想处理 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'
)
原文由 Daniel Hitchcock 发布,翻译遵循 CC BY-SA 4.0 许可协议
The issue here is that in Python 3 you need to use
StringIO
withcsv.write
andsend_file
requiresBytesIO
, so you have to do both .在 Flask 2.0 之前,
download_name
被称为attachment_filename
。