utils_hash.py 688 B

12345678910111213141516171819202122232425
  1. import hashlib
  2. def calc_hash(content, hash_object=None):
  3. hash_object = hash_object or hashlib.md5()
  4. if isinstance(hash_object, str):
  5. hash_object = hashlib.new(hash_object)
  6. hash_object.update(content)
  7. return hash_object.hexdigest()
  8. def calc_file_hash(filename, hash_object=None, chunk_size=1024 * 1024):
  9. hash_object = hash_object or hashlib.md5()
  10. if isinstance(hash_object, str):
  11. hash_object = hashlib.new(hash_object)
  12. with open(filename, "rb") as f:
  13. while True:
  14. chunk = f.read(chunk_size)
  15. if not chunk:
  16. break
  17. hash_object.update(chunk)
  18. return hash_object.hexdigest()