增量更新
散列计算器的update()方法可以反复调用。每次调用时,都会根据提供的附加文本更新摘要。增量更新比将整个文件读入内存更高效,而且能生成相同的效果。
新建hashlib_update.py文件。
import hashlib
from hashlib_data import lorem
h = hashlib.md5()
h.update(lorem.encode('utf-8'))
all_at_once = h.hexdigest()
def chunkize(size, text):
start = 0
while start < len(text):
chunk = text[start:start + size]
yield chunk
start += size
return
h = hashlib.md5()
for chunk in chunkize(64, lorem.encode('utf-8')):
h.update(chunk)
line_by_line = h.hexdigest()
print('All at once :', all_at_once)
print('Line by line:', line_by_line)
print('Same :', (all_at_once == line_by_line))
以上代码输出结果为:
All at once : 3f2fd2c9e25d60fb0fa5d593b802b7a8
Line by line: 3f2fd2c9e25d60fb0fa5d593b802b7a8
Same : True
以上代码展示了读取或生成数据时如何以增量方式更新一个摘要。