Unicode-objects must be encoded before hashing

0

The error points to this line of code:

salt=hashlib.sha1(str(random.random())).hexdigest()[:5]

Before it worked normally, but after I switched to django 1.10.3 and python 3.5 points to that error

    
asked by anonymous 01.12.2016 / 12:46

1 answer

0

This error also occurs because of the difference in Python 2 and 3 dealing differently with strings.

Python 2

>>> type(str(random.random()).encode('utf-8'))
<type 'str'>
>>> type(str(random.random()))
<type 'str'>

Python 3:

>>> type(str(random.random()))
<type 'str'>

>>> type(str(random.random()).encode('utf-8'))
<class 'bytes'>

So in order to work, you'll have to use the .encode('utf-8') method, thus:

>>> import hashlib
>>> import random
>>> hashlib.sha1(str(random.random()).encode('utf-8')).hexdigest()[:5]
'7e8ff'
    
03.12.2016 / 03:30