我需要处理一个 xml 文件并将其发送回来,将所有内容存储在内存中。我尝试使用 BytesIO 作为类似文件的对象。 最初,我尝试了这个:
with BytesIO() as file:
data.write(file, encoding='windows-1251')
return send_file(file,attachment_filename='output.xml',as_attachment=True)
这导致了以下错误:
Traceback (most recent call last):
File "/usr/lib/python3.7/site-packages/werkzeug/wsgi.py", line 580, in __next__
data = self.file.read(self.buffer_size)
ValueError: I/O operation on closed file.
但是,当我这样做时:
with BytesIO() as file:
data.write(file, encoding='windows-1251')
file.seek(0)
return send_file(BytesIO(file.read()),attachment_filename='output.xml',as_attachment=True)
一切都很顺利。有人可以向我解释第一个尝试的问题是什么以及为什么第二个尝试有效吗?
最佳答案
您正在使用 with BytesIO()
这意味着您将对其进行处理,并且 BytesIO 将保持打开状态,但您的返回值位于 with
内,换句话说,您是尝试发送它仍然会打开,因为它的内部也有with
。
在第二种情况下,您正在创建另一个 BytesIO 实例,而不使用 with
这意味着它会自行关闭该实例。
对不起,我的英语
关于xml - 使用 BytesIO 和 Flask send_file,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58197454/