0

I am trying to make a web service call in Python 3. A subset of the request includes a base64 encoded string, which is coming from a list of Python dictionaries.

So I dump the list and encode the string:

j = json.dumps(dataDictList, indent=4, default = myconverter)
encodedData = base64.b64encode(j.encode('ASCII'))

Then, when I build my request, I add in that string. Because it comes back in bytes I need to change it to string:

...
\"data\": \"''' + str(encodedData) + '''\"
...

The response I'm getting from the web service is that my request is malformed. When I print our str(encodedData) I get:

b'WwogICAgewogICAgICAgICJEQVlfREFURSI6ICIyMDEyLTAzLTMxIDAwOjAwOjAwIiwKICAgICAgICAiQ0FMTF9DVFJfSUQiOiA1LAogICAgICAgICJUT1RfRE9MTEFSX1NBTEVTIjogMTk5MS4wLAogICAgICAgICJUT1RfVU5JVF9TQUxFUyI6IDQ0LjAsCiAgICAgICAgIlRPVF9DT1NUIjogMTYxOC4xMDM3MDAwMDAwMDA2LAogICAgICAgICJHUk9TU19ET0xMQVJfU0FMRVMiOiAxOTkxLjAKICAgIH0KXQ=='

If I copy this into a base64 decoder, I get gibberish until I remove the b' at the beginning as well as the last single quote. I think those are causing my request to fail. According to this note, though, I would think that the b' is ignored: What does the 'b' character do in front of a string literal?

I'll appreciate any advice.

Thank you.

agmstrat
  • 3
  • 1

1 Answers1

1

Passing a bytes object into str causes it to be formatted for display, it doesn't convert the bytes into a string (you need to know the encoding for that to work):

In [1]: x = b'hello'

In [2]: str(x)
Out[2]: "b'hello'"

Note that str(x) actually starts with b' and ends with '. If you want to decode the bytes into a string, use bytes.decode:

In [5]: x = base64.b64encode(b'hello')

In [6]: x
Out[6]: b'aGVsbG8='

In [7]: x.decode('ascii')
Out[7]: 'aGVsbG8='

You can safely decode the base64 bytes as ASCII. Also, your JSON should be encoded as UTF-8, not ASCII. The following changes should work:

j = json.dumps(dataDictList, indent=4, default=myconverter)
encodedData = base64.b64encode(j.encode('utf-8')).decode('ascii')
Blender
  • 289,723
  • 53
  • 439
  • 496