Python ';字节';对象没有属性';编码';

Python ';字节';对象没有属性';编码';,python,python-3.x,bcrypt,Python,Python 3.x,Bcrypt,我试图在将每个文档插入集合之前存储salt和哈希密码。但在对salt和密码进行编码时,会显示以下错误: 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 d

我试图在将每个文档插入集合之前存储salt和哈希密码。但在对salt和密码进行编码时,会显示以下错误:

 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中使用eve框架,并使用Python3.4

您正在使用的:bcrypt.gensalt() bcrypt.gensalt() 此方法似乎生成了一个bytes对象。这些对象没有任何编码方法,因为它们只处理与ASCII兼容的数据。因此,您可以尝试不使用.encode('utf-8')

来自
.getsalt()
方法的salt是一个bytes对象,bcrypt模块的方法中的所有“salt”参数都希望它以这种特定的形式出现。没有必要将其转换为其他内容

与之相反,bcrypt模块方法中的“password”参数应该是Unicode字符串的形式——在Python3中,它只是一个字符串

所以-假设您的原始
文档['password']
是一个字符串,那么您的代码应该是

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

你没有试着对它进行编码吗?是的,如果我只是使用
document['salt']=bcrypt.gensalt()
它会显示“在hashpw中,raise TypeError(“Unicode对象必须在散列之前进行编码”)TypeError:Unicode对象必须在散列之前进行编码”@jornsharpeit看起来像
bcrypt
正在返回一个
字节
实例,它不能被编码。如果需要,它可以被解码。编码=
str
字节
,解码=
字节
str
究竟是什么在抱怨
TypeError
具体在哪里?它在
bcrypt.hashpw
处显示
TypeError
,并且它说
Unicode对象必须在散列之前进行编码
您的问题不是不能对
bcrypt.gensalt()的结果进行编码。你绝对不能,它已经是一个
字节
对象了。您的问题是,
bcrypt.hashpw
中有一个unicode对象!这些对象没有
encode
方法。。。因为编码一个
字节
对象毫无意义。原始
字节
可以根据特定字符集对字符进行解码(
str
),反之亦然。