Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

b64encode when going from Python2 to Python3

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?

like image 642
GreenGodot Avatar asked Sep 22 '15 14:09

GreenGodot


People also ask

Are Python 2 and Python 3 are interchangeable?

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.

What is base64 b64decode in Python?

b64decode() in Python. The base64. b4() function in Python decodes strings or byte-like objects encoded in base64 and returns the decoded bytes.

Is Python 3 slower than python2?

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.


3 Answers

b64encode accepts bytes and returns bytes. To merge with string, do also decode.

'Authorization': 'Basic ' + b64encode(auth_string.encode()).decode()
like image 89
pacholik Avatar answered Sep 30 '22 12:09

pacholik


in Python3, strings are either bytes or unicode.

Just prefix your strings with b:

b'Basic ' + b64encode(auth_string.encode(encoding='utf_8'))
like image 28
DevLounge Avatar answered Sep 30 '22 12:09

DevLounge


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')
like image 27
Garet Avatar answered Sep 30 '22 13:09

Garet