2016-07-07 80 views
2

我試圖存儲的鹽和在編碼的鹽和密碼將每個文件劃分成collection.But前散列密碼,則顯示以下錯誤:「字節」對象沒有屬性「編碼」

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與Python 3.4

+3

你嘗試*不*'encode'-ING呢? – jonrsharpe

+0

是的,如果我只是使用'document ['salt'] = bcrypt.gensalt()'它顯示「在hashpw raise TypeError(」Unicode-對象必須在散列之前編碼) TypeError:必須編碼Unicode-對象哈希之前「@jonrsharpe – DEVV911

+0

它看起來像'bcrypt'返回一個'字節'的實例,*不能*編碼。如果需要,它可以被解碼。 Encoding ='str'爲'bytes',decode ='bytes'爲'str'。 - 究竟是在抱怨一個'TypeError'究竟在哪裏? – deceze

回答

2

您使用:

bcrypt.gensalt()
這種方法似乎會生成一個字節對象。這些對象沒有任何編碼方法,因爲它們只能使用ASCII兼容的數據。所以,你可以嘗試沒有 .encode( 'UTF-8')

Bytes description in python 3 documentation

+0

這些對象沒有'encode'方法...因爲編碼一個字節對象是沒有意義的。原始的'bytes'可以根據特定的字符集來解碼*字符*('str'),而不是相反。 – deceze

相關問題