Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/338.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从werkzeug.datastructures.FileStorage计算md5,而不将对象另存为文件_Python_Flask - Fatal编程技术网

Python 从werkzeug.datastructures.FileStorage计算md5,而不将对象另存为文件

Python 从werkzeug.datastructures.FileStorage计算md5,而不将对象另存为文件,python,flask,Python,Flask,我用Flask上传文件。 为了防止将同一个文件存储两次,我打算从文件内容中计算md5,并将文件存储为。除非文件已经存在 @app.route('/upload', methods=['GET', 'POST']) def upload_file(): if request.method == 'POST': file = request.files['file'] #next line causes exception img_key =

我用Flask上传文件。 为了防止将同一个文件存储两次,我打算从文件内容中计算md5,并将文件存储为。除非文件已经存在

@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()
不幸的是,hashlib.md5引发了异常:

TypeError: must be string or buffer, not FileStorage
我已经尝试过file.stream-同样的效果

有没有办法从文件中获取md5而不临时保存它?

从文件中

档案

作为POST或PUT的一部分上载文件的多目录 要求每个文件都存储为文件存储对象。基本上 其行为类似于Python中的标准文件对象,具有 区别在于它还有一个save()函数可以存储文件 在文件系统上

如果它与文件对象相同,则应该能够执行此操作

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

request.files['file']
属于
FileStorage
类型,具有
read()
方法。 试着做:

file = request.files['file']

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

有关
文件存储的更多信息

hmm。。我认为文件存储已经使用了一个临时文件。谢谢!我是python初学者。现在看起来很明显。不幸的是,调用file.read()后,文件似乎变为空。因此,在调用file.save()之后,我得到了内容为0的文件。@ValentinHeinitz:使用
file.seek(0)
倒带文件指针。我会分块执行此操作,以避免仅仅为了计算MD5而将整个内容读入内存。