3

I have to make a post to a rest server in python. In header authentication I have to include a base64 encoded string.

I do it with base64 module:

import base64
#node here is '3180' but I also tried with text
node = base64.b64encode(node.encode('utf-8'))
node = 'Basic ' + str(node)
headers = {'Content-type': 'application/json', 'Authentication': node}
print(headers)

And what I get in print is:

{'Authentication': "Basic b'MzE4MA=='", 'Content-type': 'application/json'}

Which has b' ... ' added to node base64 string. Is there a way to avoid those characters to appear? I don't know if they just appears in prints or also are sent to the server.

1 Answer 1

6

b64encode is returning bytes instead of a str. When you call str() on it without specifying an encoding, instead of converting the value, it's actually giving you the Python representation of the bytes object which is b'MzE4MA=='.

To avoid this use node = 'Basic ' + node.decode('ascii')

Note that you could also use str(node, encoding='ascii') but this is longer.

Sign up to request clarification or add additional context in comments.

Comments

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.