Jus*_*ory 5 python string encoding utf-8 python-3.x
我正在努力将现有程序从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]
Run Code Online (Sandbox Code Playgroud)
此方法的问题是在将整数转换为字符串后,需要对其进行编码.但据我所知,它已经编码了?我发现了这个问题,但我很难将其应用到该程序的上下文中.
这是给我带来问题的路线.
+ 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的中级知识),所以我还不完全熟悉这门语言.有没有人对这个问题有什么想法?
谢谢!
Oek*_*hny 11
此错误是由于您在python 3中创建字节的方式.
你不会这样做bytes("bla bla")
,只是b"blabla"
或者你需要指定一个编码类型,bytes("bla bla","utf-8")
因为它需要知道什么是原始编码,然后再将其转换为数字数组.
然后是错误
TypeError: string argument without an encoding
Run Code Online (Sandbox Code Playgroud)
应该消失.
你有字节或str.如果你有一个字节值,你想在str中打开它,你应该这样做:
my_bytes_value.decode("utf-8")
Run Code Online (Sandbox Code Playgroud)
它会让你回归.
我希望它有所帮助!祝你今天愉快 !