Python 'bytes' 对象没有属性 'encode'

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38246412/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 20:33:28  来源:igfitidea点击:

'bytes' object has no attribute 'encode'

pythonpython-3.xbcrypt

提问by DEVV911

I'm trying to store salt and hashed password before inserting each document into a collection. But on encoding the salt and password, it shows the following error:

我试图在将每个文档插入集合之前存储盐和散列密码。但是在对盐和密码进行编码时,它显示以下错误:

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

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

This is my code:

这是我的代码:

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'])

I'm using eve framework in virtualenv with python 3.4

我在 virtualenv 中使用 eve 框架和 python 3.4

回答by Kreu

You're using :

您正在使用:

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

Bytes description in python 3 documentation

python 3文档中的字节描述

回答by MarianD

The saltfrom the .getsalt()method is a bytes object, and all the "salt" parameters in the methods of bcrypt module expect it in this particular form. There is no need to convert it to something else.

.getsalt()方法是一个字节对象,并且在bcrypt模块的方法的所有的“盐”参数期望它在这一特定形式。无需将其转换为其他内容。

In contrast to it, the "password" parameters in methods of bcrypt module are expected it in the form of the Unicode string- in Python 3 it is simply a string.

与此相反, bcrypt 模块方法中的“密码”参数需要以Unicode 字符串的形式出现- 在 Python 3 中它只是一个string

So - assuming that your original document['password']is a string, your code should be

所以 - 假设你的原件document['password']是一个字符串,你的代码应该是

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