我想处理 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 中,您需要将 StringIO
与 csv.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/