Python File object to Flask's FileStorage
http://werkzeug.pocoo.org/docs/0.11/datastructures/#werkzeug.datastructures.FileStorage
I needed to use the flask FileStorage
object for a utility outside of the testing framework and the application itself, essentially replicating how uploading a file works using a form. This worked for me.
from werkzeug.datastructures import FileStoragefile = Nonewith open('document-test/test.pdf', 'rb') as fp: file = FileStorage(fp)file.save('document-test/test_new.pdf')
The get
and post
methods of the Flask test client invoke werkzeug.test.EnvironBuilder
under the hood - so if you pass in a dictionary as the keyword argument data
with your file you should be able to work with it then:
def test_upload(): with open("document-test/test.pdf", "rb") as your_file: self.app.post("/upload", data={"expected_file_key": your_file}) # Your test here
@neurosnap 's answer got me started but didn't quite work. The following did...
file_loc = open('./tests/sample data/2 Candidates.csv', 'rb')file = werkzeug.datastructures.FileStorage(file_loc)file.save(dst='document-test/test_new.pdf')file_loc.close()
Python throws an error if you don't close the file at the end.