python b64encode_从Python2到Python3时的b64encode

我正在运行一些在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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值