我正在努力转换现有计划从Python2到Python3。该程序中的方法之一通过远程服务器对用户进行身份验证。它将提示用户输入密码。
def _handshake(self):
timestamp = int(time.time())
token = (md5hash(md5hash((self.password).encode('utf-8')).hexdigest()
+ str(bytes('timestamp').encode('utf-8'))))
auth_url = "%s/?hs=true&p=1.2&u=%s&t=%d&a=%s&c=%s" % (self.name,
self.username,
timestamp,
token,
self.client_code)
response = urlopen(auth_url).read()
lines = response.split("\n")
if lines[0] != "OK":
raise ScrobbleException("Server returned: %s" % (response,))
self.session_id = lines[1]
self.submit_url = lines[3]
这种方法的问题在于,整数转换为字符串后,需要进行编码。但据我所知,它已经被编码了?我发现这个问题但我很难将其应用到这个程序的上下文中。
这是给我带来问题的线路。
-
+ str(bytes('timestamp').encode('utf-8'))))
TypeError: string argument without an encoding
我尝试过使用其他方法来执行此操作,但都存在不同类型的错误。
-
+ str(bytes('timestamp', 'utf-8'))))
TypeError: Unicode-objects must be encoded before hashing
-
+ str('timestamp', 'utf-8')))
TypeError: decoding str is not supported
我仍在开始学习Python(但我有Java的初级到中级知识),所以我还没有完全熟悉这门语言。有人对这个问题可能是什么有任何想法吗?
Thanks!
此错误是由于您在 python 3 中创建字节的方式造成的。
你不会做bytes("bla bla")
只是b"blabla"
或者您需要指定编码类型,例如bytes("bla bla","utf-8")
因为它需要知道原始编码是什么,然后才能将其转换为数字数组。
然后错误
TypeError: string argument without an encoding
应该消失。
您有 bytes 或 str。如果你有一个 bytes 值并且想将其转换为 str 你应该这样做:
my_bytes_value.decode("utf-8")
它会返回给你一个str。
我希望它有帮助!祝你今天过得愉快 !
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)