Python File Object for Flask FileStorage

I am trying to test my upload () method in Flask. The only problem is that the FileStorage object in Flask has a save () method that the python File object does not have.

I create my file as follows:

file = open('documents-test/test.pdf') 

But I can not check my upload () method, because this method uses save ().

Any ideas on how to convert this File object to a Flask Filestorage object?

+6
source share
2 answers

http://werkzeug.pocoo.org/docs/0.11/datastructures/#werkzeug.datastructures.FileStorage

I needed to use the FileStorage flag FileStorage for a utility outside the scope of testing and the application itself, substantially replicating how file loading works using the form. It worked for me.

 from werkzeug.datastructures import FileStorage file = None with open('document-test/test.pdf', 'rb') as fp: file = FileStorage(fp) file.save('document-test/test_new.pdf') 
+8
source

The get and post methods of the Flask test client call werkzeug.test.EnvironBuilder under the hood - so if you go through the dictionary as an argument to the data keyword with your file, you can work with it:

 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 
0
source

Source: https://habr.com/ru/post/951792/


All Articles