【发布时间】:2018-11-10 06:45:51
【问题描述】:
我已经查看了此处的其他 4 个问题,但仍然无法弄清楚将 .encode() 或 .encode('utf-8') 放在哪里。我已将其注释掉以显示我尝试过的各个地方。
import hashlib as hasher
class Block:
def __init__(self, index, timestamp, data, previous_hash):
self.index = index
self.timestamp = timestamp
self.data = data
self.previous_hash = previous_hash #these four items used to calculate crypHash of each block
self.hash = self.hash_block() #helps ensure integrity throughout blockchain
def hash_block(self):
sha = hasher.sha256() #.encode('utf-8')
sha.update(str(self.index)+
str(self.timestamp)+
str(self.data)+
str(self.previous_hash)) #.encode() inside brackets
return sha.hexdigest()
这是 Traceback(自下而上阅读):
Traceback (most recent call last):
File "blockchain.py", line 7, in <module>
blockchain = [create_genesis_block()]
File "/media/nobu/win10Files/Blockchain/SnakeCoin/genesis.py", line 8, in create_genesis_block
return Block(0, date.datetime.now(), "Genesis Block", "0")
File "/media/nobu/win10Files/Blockchain/SnakeCoin/block.py", line 9, in __init__
self.hash = self.hash_block() #helps ensure integrity throughout blockchain
File "/media/nobu/win10Files/Blockchain/SnakeCoin/block.py", line 16, in hash_block
str(self.previous_hash))
TypeError: Unicode-objects must be encoded before hashing
这似乎表明str(self.previous_hash)) #.encode() inside brackets 应该是str(self.previous_hash).encode()) 但这给了我另一个错误:
Traceback (most recent call last):
File "blockchain.py", line 7, in <module>
blockchain = [create_genesis_block()]
File "/media/nobu/win10Files/Blockchain/SnakeCoin/genesis.py", line 8, in create_genesis_block
return Block(0, date.datetime.now(), "Genesis Block", "0")
File "/media/nobu/win10Files/Blockchain/SnakeCoin/block.py", line 9, in __init__
self.hash = self.hash_block() #helps ensure integrity throughout blockchain
File "/media/nobu/win10Files/Blockchain/SnakeCoin/block.py", line 16, in hash_block
str(self.previous_hash).encode())
TypeError: must be str, not bytes
所以我尝试了 encode() 和 decode() 与括号的各种组合,但这只会让我在错误之间交替。
因此,我很迷茫,希望得到一些指导。
顺便说一句,这段代码来自这里的一篇 Medium 文章:Medium Snake Coin
【问题讨论】:
-
在编码前连接整个字符串:
sha.update((str(self.index) + str(self.timestamp) + str(self.data) + str(self.previous_hash)).encode())。update()接受一个字符串。这可能会有所帮助:docs.python.org/2/library/hashlib.html
标签: python hash encoding typeerror