简体   繁体   English

是否有可能在python中获取临时文件的md5哈希?

[英]Is it possible to get the md5 hash of a tempfile in python?

I'm getting an attachment from an email Message object and creating a tempfile like so: 我从电子邮件对象获取附件,并创建一个临时文件,如下所示:

import tempfile

with tempfile.NamedTemporaryFile() as temp:
    temp.write(payload.get_payload(decode=True))

Is it possible to get the md5 out of this tempfile or do I have to save it to disk and then get the md5? 是否可以从此临时文件中获取md5,还是必须将其保存到磁盘上然后获取md5? Something like so would be what I'm aiming for: 我的目标是:

import hashlib
print(hashlib.md5(temp).hexdigest())

But I run into this error 但是我遇到了这个错误

TypeError: object supporting the buffer API required

When you call the hashlib.md5 command it does expect a string like object instead of a file handle. 当您调用hashlib.md5命令时,它确实期望像对象这样的字符串而不是文件句柄。 But guess what you already have that. 但是,请猜您已经拥有了什么。 So there is no need to read it back from the file. 因此,无需从文件中读回它。

import tempfile
import hashlib

with tempfile.NamedTemporaryFile() as temp:
    data = payload.get_payload(decode=True)
    temp.write(data)
    print(hashlib.md5(data).hexdigest())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM