I'm trying to test my upload() method in Flask. The only problem is that the FileStorage object in Flask has a method save() which the python File object does not have.
I create my file like this:
file = open('documents-test/test.pdf')
But I cannot test my upload() method because that method uses save().
Any ideas how to convert this File object to a Flask Filestorage object?
The FileStorage class is a thin wrapper over incoming files. It is used by the request object to represent uploaded files. All the attributes of the wrapper stream are proxied by the file storage so it's possible to do storage. read() instead of the long form storage.
To create a file object in Python use the built-in functions, such as open() and os. popen() . IOError exception is raised when a file object is misused, or file operation fails for an I/O-related reason. For example, when you try to write to a file when a file is opened in read-only mode.
Python for web development using Flask Handling file upload in Flask is very easy. It needs an HTML form with its enctype attribute set to 'multipart/form-data', posting the file to a URL. The URL handler fetches file from request. files[] object and saves it to the desired location.
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 FileStorage
file = None
with open('document-test/test.pdf', 'rb') as fp:
file = FileStorage(fp)
file.save('document-test/test_new.pdf')
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