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

I use Flask to upload files. To prevent saving the same file twice, I am going to calculate md5 from the contents of the file and save the file as. if the file already exists.

@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()

Unfortunately, hashlib.md5 throws an exception:

TypeError: must be string or buffer, not FileStorage

I already tried file.stream - same effect.

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

+4
source share
2 answers

request.files['file']has a type FileStoragethat a method has read(). Try to do:

file = request.files['file']

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

Further information on FileStorage: http://werkzeug.pocoo.org/docs/datastructures/#werkzeug.datastructures.FileStorage

+7

MultiDict , POST PUT . FileStorage. , Python, , save(), .

, ,

img_key = hashlib.md5(file.read()).hexdigest()
+2

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


All Articles