“bytes”对象没有“encode”属性

2024-05-15 03:05:56 发布

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

我试图在将每个文档插入到集合之前存储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框架和python 3.4


Tags: in文档密码编码错误passworddocumentdocuments
2条回答

您正在使用:

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

Bytes description in python 3 documentation

来自.getsalt()方法的salt是一个bytes对象,bcrypt模块的方法中的所有“salt”参数都期望它以这种特殊的形式出现。没有必要把它转换成别的东西。

与之相反,bcrypt模块的方法中的“password”参数应该是以Unicode字符串的形式出现的-在Python 3中,它只是一个字符串而已。

因此-假设您的原始document['password']是一个字符串,那么您的代码应该是

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

相关问题 更多 >

    热门问题