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

Viewed 728

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? 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
1 Answers

When you call the hashlib.md5 command it does expect a string like object instead of a file handle. 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())
Related