utils_hash.py 656 B

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