2016-07-07 77 views
2

我试图存储的盐和在编码的盐和密码将每个文件划分成collection.But前散列密码,则显示以下错误:“字节”对象没有属性“编码”

line 26, in before_insert 
document['salt'] = bcrypt.gensalt().encode('utf-8') 

AttributeError: 'bytes' object has no attribute 'encode' 

这是我的代码:

def before_insert(documents): 
    for document in documents: 
     document['salt'] = bcrypt.gensalt().encode('utf-8') 
     password = document['password'].encode('utf-8') 
     document['password'] = bcrypt.hashpw(password, document['salt']) 

我使用前夕框架的virtualenv与Python 3.4

+3

你尝试*不*'encode'-ING呢? – jonrsharpe

+0

是的,如果我只是使用'document ['salt'] = bcrypt.gensalt()'它显示“在hashpw raise TypeError(”Unicode-对象必须在散列之前编码) TypeError:必须编码Unicode-对象哈希之前“@jonrsharpe – DEVV911

+0

它看起来像'bcrypt'返回一个'字节'的实例,*不能*编码。如果需要,它可以被解码。 Encoding ='str'为'bytes',decode ='bytes'为'str'。 - 究竟是在抱怨一个'TypeError'究竟在哪里? – deceze

回答

2

您使用:

bcrypt.gensalt()
这种方法似乎会生成一个字节对象。这些对象没有任何编码方法,因为它们只能使用ASCII兼容的数据。所以,你可以尝试没有 .encode( 'UTF-8')

Bytes description in python 3 documentation

+0

这些对象没有'encode'方法...因为编码一个字节对象是没有意义的。原始的'bytes'可以根据特定的字符集来解码*字符*('str'),而不是相反。 – deceze

相关问题