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?
Python version 3 is not backwardly compatible with Python 2. Many recent developers are creating libraries which you can only use with Python 3. Many older libraries created for Python 2 is not forward-compatible.
b64decode() in Python. The base64. b4() function in Python decodes strings or byte-like objects encoded in base64 and returns the decoded bytes.
maxint was dropped from Python 3, but the integer value is basically the same. The speed difference in Python 2 is thus limited to the first (2 ** 63) - 1 integers on 64-bit, (2 ** 31) - 1 integers on 32 bit systems.
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With