Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate md5 from werkzeug.datastructures.FileStorage without saving the object as file

Tags:

python

flask

I'm using Flask for uploading files. In order to prevent storing same file twice, I'm intending to calculate md5 from the file content, and store the file as . unless the file is already there.

@app.route('/upload', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        file = request.files['file']
        #next line causes exception
        img_key = hashlib.md5(file).hexdigest()

Unfortunatelly, hashlib.md5 throws the exception:

TypeError: must be string or buffer, not FileStorage

I've already tried file.stream - same effect.

Is there any way to get md5 from the file without saving it temporarily?

like image 415
Valentin H Avatar asked Jul 04 '14 08:07

Valentin H


People also ask

How do I get files out of a 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.

What is werkzeug datastructures?

Werkzeug provides some subclasses of common Python objects to extend them with additional features. Some of them are used to make them immutable, others are used to change some semantics to better work with HTTP.


2 Answers

request.files['file'] is of type FileStorage which has a read() method. Try doing:

file = request.files['file']

#file.read() is the same as file.stream.read()
img_key = hashlib.md5(file.read()).hexdigest() 

More info on FileStorage: http://werkzeug.pocoo.org/docs/datastructures/#werkzeug.datastructures.FileStorage

like image 92
data Avatar answered Sep 29 '22 16:09

data


From the Flask docs

files

A MultiDict with files uploaded as part of a POST or PUT request. Each file is stored as FileStorage object. It basically behaves like a standard file object you know from Python, with the difference that it also has a save() function that can store the file on the filesystem.

If it's the same as a file object you should be able to do this

img_key = hashlib.md5(file.read()).hexdigest()
like image 42
Stack of Pancakes Avatar answered Sep 29 '22 17:09

Stack of Pancakes