'bytes' object has no attribute 'encode'

一曲冷凌霜 提交于 2019-12-18 18:54:26

问题


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


回答1:


You're using :

bcrypt.gensalt()
This method seems to generate a bytes object. These objects do not have any encode methods as they only work with ASCII compatible data. So you can try without .encode('utf-8')

Bytes description in python 3 documentation




回答2:


The salt from 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.

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.

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

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


来源:https://stackoverflow.com/questions/38246412/bytes-object-has-no-attribute-encode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!