使用多处理时,Hashlib返回重复的哈希

2024-09-30 06:14:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用hashlib创建一个文件的sha256散列,然后将其与存储在数据库中的文件的先前哈希进行比较。在

def create_hash(file, id, hex=True, hash_type=hashlib.sha256):
    con = db.connect(db_host, db_user, db_pass, db_db)
    cur = con.cursor()
    hashinst = hash_type()
    with open(file, 'rb') as f:
            for chunk in iter(lambda: f.read(hashinst.block_size * 128), b''):
                hashinst.update(chunk)
            hash = hashinst.hexdigest() if hex else hashinst.digest()
    print hash
    cur.execute("SELECT * FROM Previews WHERE S_Id=%s", (id))
    row = cur.fetchone()
    count = row[2] + 1
    cur_hash = row[1]
    if hash == cur_hash:
        count = row[2] + 1
        cur.execute("UPDATE Previews SET Count = %s WHERE S_Id = %s", (count, id))
        con.commit()
    elif hash != cur_hash:
        cur.execute("UPDATE Previews SET Count = 0 WHERE S_Id = %s", (id))
        con.commit()
        cur.execute("UPDATE Previews SET Hash = %s WHERE S_Id = %s", (hash, id))    
        con.commit()

速度是必须的,所以我也使用多处理模块。在

^{pr2}$

这将调用一个函数create_preview,该函数创建图像并调用上面的函数。问题是所有的哈希都是一样的。如果我在for循环中这样做,而不是使用多处理池,我就没有问题,而且所有的哈希都是不同的。在

有人知道使用hashlib模块和多处理或其他方法比较文件时可能出现的问题吗?在


Tags: 文件idexecutedbcountupdatehashwhere

热门问题