Unicode-Objects must be encoded before hashing

Asked

Viewed 2,713 times

0

The error points to that line of code:

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

It used to work normally, but after I passed to Django 1.10.3 and python 3.5 points out this error

1 answer

0


This error is also due to the difference that Python 2 and 3 handle strings differently.

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 to work, you’ll have to use the method .encode('utf-8'), being like this:

>>> import hashlib
>>> import random
>>> hashlib.sha1(str(random.random()).encode('utf-8')).hexdigest()[:5]
'7e8ff'
  • now pointing to the same error but to the line below: activation_key=hashlib.sha1(salt+user.email). hexdigest()

  • Same reason as the previous one. You have to use the method .encode. activation_key=hashlib.sha1(str(salt+user.email).encode('utf-8')).hexdigest()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.