7

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?

3 Answers 3

6

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

'Authorization': 'Basic ' + b64encode(auth_string.encode()).decode()
Sign up to request clarification or add additional context in comments.

1 Comment

That did the trick! Thanks a bunch. Looks like I forgot you need to merge with the string as well.
2

in Python3, strings are either bytes or unicode.

Just prefix your strings with b:

b'Basic ' + b64encode(auth_string.encode(encoding='utf_8'))

Comments

1

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')

3 Comments

I think you mean to use "encoding=" instead of "encode=" as the latter is an invalid keyword. Your first method at least does not work. Is it possible to prefix a string object? e.g. (b''auth_code)?
Yes, the param name is "encoding", sorry.
You cannot use prefix with objects. Should use bytes(mystring.encode(encoding='ascii')) or bytes(mystring.encode('ascii'))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.