I am running some code that runs on on Python2 to Python3 and it is having some issues. I have a string with formatting:
auth_string = '{client_id}:{client_secret}'.format(client_id=client_id, client_secret=client_secret)
and am passing it in as part of "headers":
headers = {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
'Authorization': 'Basic ' + b64encode(auth_string)
}
When I run the code I get this error:
TypeError: 'str' does not support the buffer interface
After some research, it is because Python3 considers strings as unicode objects and you need to convert them to bytes first. No problem, I change the line to:
'Authorization': 'Basic ' + b64encode(auth_string.encode(encoding='utf_8'))
But now I get a new error:
TypeError: Can't convert 'bytes' object to str implicitly
What exactly am I missing here?
b64encode
accepts bytes
and returns bytes
. To merge with string, do also decode
.
'Authorization': 'Basic ' + b64encode(auth_string.encode()).decode()
in Python3, strings are either bytes or unicode .
Just prefix your strings with b :
b'Basic ' + b64encode(auth_string.encode(encoding='utf_8'))
You should cast your str var to a bytes var:
To cast str to bytes str should be content only ascii chars.
base64.64encode(auth_string.encode(encoding='ascii'))
or
base64.64encode(b'bytes string')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.