'bytes' object has no attribute 'encode'

DEVV911 picture DEVV911 · Jul 7, 2016 · Viewed 84.8k times · Source

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

Answer

Kreu picture Kreu · Jul 7, 2016

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