gpt4 book ai didi

python - 为什么对于 API 调用中为输入文件创建的每个新临时文件,哈希考虑相同的值?

转载 作者:行者123 更新时间:2023-12-01 09:29:28 27 4
gpt4 key购买 nike

我有一个 API 调用,它从表单中获取文件输入并为创建的临时文件生成哈希 key 。但是,当选择不同的文件作为输入文件时,会生成相同的哈希值。API 调用的代码片段如下:(排除其他不相关的代码)

 def gen_hash():
for attr, document in request.files.iteritems():
orig_filename = document.filename
new_doc = add_doc(orig_filename, orig_filename)
#mhash = None
##############
# hashing algorithm checks the contents of the file if
# modified before uploading to destination, NOT file name
try:
tmp1 = tempfile.NamedTemporaryFile(delete=False)
tmp1.write(document.read())
tmp1.seek(0)
# for chunk in iter(lambda: tmp1.read(128* sha1().block_size),
# b""):
for chunk in iter(lambda: tmp1.read(128), b""):
sha1().update(chunk)
mhash1 = sha1().hexdigest()
print mhash1
finally:
#print e
os.unlink(tmp1.name)

使用flask v.0.12,python 2.7。为什么不同文件内容的哈希 key 相同?

最佳答案

hashlib.sha1()创建一个 SHA-1 哈希对象,您可以使用数据更新该对象并最终获得摘要。但你并没有保存那个对象。为每个 block 创建并丢弃一个新对象,然后创建另一个空摘要并获取其值。你总是对相同的空序列进行哈希处理并得到 da39a3ee5e6b4b0d3255bfef95601890afd80709 .

因为您在一个 read 中获取了整个文档将其写入临时文件并进行分块读取没有任何优势。只需对您抓取的数据进行哈希处理即可。

def gen_hash():
for attr, document in request.files.iteritems():
orig_filename = document.filename
new_doc = add_doc(orig_filename, orig_filename)
mhash1 = sha1(document.read()).hexdigest()
print mhash1

假设document是一个类似文件的对象,您可以分块更新哈希并避免一次读取整个文档的内存成本。

def gen_hash():
for attr, document in request.files.iteritems():
orig_filename = document.filename
new_doc = add_doc(orig_filename, orig_filename)
hash = sha1()
for chunk in iter(lambda: document.read(65536), ''):
hash.update(chunk)
mhash1 = hash.hexdigest()
print mhash1

何时 iter使用 2 个参数调用,第一个是生成数据的函数,第二个是迭代的结束条件。所以,iter(lambda: document.read(65536), '')不断调用从 document 读取数据的函数直到什么都没有为止。

关于python - 为什么对于 API 调用中为输入文件创建的每个新临时文件,哈希考虑相同的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50088189/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com