我正在运行一些在Python2上运行到Python3的代码,它有一些问题.我有一个格式化的字符串:
auth_string = '{client_id}:{client_secret}'.format(client_id=client_id, client_secret=client_secret)
并将其作为“标题”的一部分传递:
headers = {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
'Authorization': 'Basic ' + b64encode(auth_string)
}
当我运行代码时,我收到此错误:
TypeError: 'str' does not support the buffer interface
经过一些研究,这是因为Python3将字符串视为unicode对象,您需要先将它们转换为字节.没问题,我改行:
'Authorization': 'Basic ' + b64encode(auth_string.encode(encoding='utf_8'))
但现在我收到一个新错误:
TypeError: Can't convert 'bytes' object to str implicitly
我到底错过了什么?
解决方法:
b64encode接受字节并返回字节.要与字符串合并,请同时解码.
'Authorization': 'Basic ' + b64encode(auth_string.encode()).decode()
标签:python,encoding,python-3-x
来源: https://codeday.me/bug/20190528/1169061.html