【发布时间】:2016-10-02 18:40:08
【问题描述】:
我正在努力将existing program 从 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]
这种方法的问题是整数转换为字符串后,需要进行编码。但据我所知,它已经编码了吗?我找到了this question,但我很难将它应用到这个程序的上下文中。
这是给我带来问题的行。
-
+ 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 有初级到中级的知识),所以我对这门语言还不是很熟悉。有人对这个问题可能有什么想法吗?
谢谢!
【问题讨论】:
-
我注意到链接中的代码已将该行更改为
+ str(timestamp)).hexdigest())这可能需要做什么? -
str(bytes('timestamp').encode('utf-8'))- 什么鬼?你想在那里做什么? -
@TadhgMcDonald-Jensen 原来是这样,但是当我尝试运行脚本时(例如
+ str(b'timestamp').hexdigest()))),我收到了AttributeError: 'str' object has no attribute 'hexdigest'作为回报。可能是,但我不太确定这一点。 -
@user2357112 我一直在尝试各种组合来使这条线正确,今天它经历了许多形式......最终,我试图让这个整数转换为一种格式Py3 将被视为有效。
-
你明白
timestamp是一个名字,'timestamp'是一个字符串文字(与timestamp名字无关)吗?这里不需要字节。在 Python 中将整数转换为字符串:str(timestamp)。使用urllib.parse.urlencode()创建查询。传递str对象(Python 中的 Unicode)。您可能需要在.hexdigest()结果上调用.decode('ascii', 'strict'),以获取str而不是bytes。
标签: python string python-3.x encoding utf-8