Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python File object to Flask's FileStorage

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?

like image 243
arnoutaertgeerts Avatar asked Aug 15 '13 09:08

arnoutaertgeerts


People also ask

What is FileStorage Python?

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.

How do you create a file object in Python?

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.

How do I upload files to flask?

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.


1 Answers

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')
like image 139
neurosnap Avatar answered Sep 20 '22 18:09

neurosnap