I need to process an xml file and send it back, storing all in-memory. I tried to use BytesIO as a file-like object. Initially, I tried this:
with BytesIO() as file:
data.write(file, encoding='windows-1251')
return send_file(file,attachment_filename='output.xml',as_attachment=True)
Which resulted in the following error:
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.
However, when I do so:
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)
Everything works out fine. Can somebody explain to me what the problem with the first one is and why the second attempt works?
You're using with BytesIO() which means that you will work on it and BytesIO will stand open but your returnment is inside with in another words, you are trying send it still opens beacuse its inside with too.
On second situation you're creating another instance of BytesIO without using with what means it close the instance by itself.
Sorry by my english
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With