PYTHON3编码错误:TypeError:需要类似字节的对象,而不是'str'

时间:2017-11-19 10:09:20

标签: python-3.x

我正在尝试将Python 2脚本转换为Python3。

如果我使用最初用Python2编写的这部分:

Traceback (most recent call last):
  File "untitled.py", line 92, in <module>
    s = login(WEB, USERNAME, PASSWORD)
  File "untitled.py", line 44, in login
    data = login_data(username, password, csrf_tokens[1])
  File "untitled.py", line 66, in login_data
    password_hash = encrypt(username + encrypt(password) + csrf_token)
  File "untitled.py", line 63, in encrypt
    m.update(text)
TypeError: Unicode-objects must be encoded before hashing

我收到错误:

def login_data(username, password, csrf_token):
    def encrypt(text):
        m = hashlib.sha256()
        m.update(text.encode())
        return base64.b64encode(m.hexdigest())

    password_hash = encrypt(username + encrypt(password) + csrf_token)
    return '<?xml version:"1.0" encoding="UTF-8"?><request><Username>admin</Username><Password>'+password_hash+'</Password><password_type>4</password_type></request>'

如果我尝试添加编码:

Traceback (most recent call last):
  File "untitled.py", line 92, in <module>
    s = login(WEB, USERNAME, PASSWORD)
  File "untitled.py", line 44, in login
    data = login_data(username, password, csrf_tokens[1])
  File "untitled.py", line 66, in login_data
    password_hash = encrypt(username + encrypt(password) + csrf_token)
  File "untitled.py", line 64, in encrypt
    return base64.b64encode(m.hexdigest())
  File "/usr/local/lib/python3.5/base64.py", line 59, in b64encode
    encoded = binascii.b2a_base64(s)[:-1]
TypeError: a bytes-like object is required, not 'str'

我收到错误:

timeone

你能帮帮我吗?

0 个答案:

没有答案