1

Hello i want to send a multipart/form-data form to a pubsub

i have the following data:

data = {'uuid' : mId, 'token' : 'd8sd87dvttd', 'objId': str(objData[1].objectID)}
img = cv2.imencode('.jpg', objData[1].getImage())[1].tostring()
post_data = { 'image' : img }
future = self.publisher.publish(
                        self.topic_path, files = json.dumps(post_data).encode('utf-8'), data=json.dumps(data).encode('utf-8'), type="data1"
                    )

this code returns the following error:

TypeError: Object of type 'bytes' is not JSON serializable

any one can help me ? i cant find any example of how to send images to pubsub google.

Jasar Orion
  • 626
  • 7
  • 26

1 Answers1

1

PubSub messages do not have any concept of images, they just contain data that must be a binary string (Python type bytes). Your form data thus needs to be encoded as a binary string before it can be published as a PubSub message.

The error you are seeing does not happen in the publish() method, but instead when the code tries to serialize one of the arguments to JSON, example:

>>> import json
>>> json.dumps({'foo': b'bar'})  # <-- bar is a BYTE string
...
TypeError: Object of type bytes is not JSON serializable

Check the contents of data and post_data for any binary strings, with img being the main suspect. You will need to convert it to text data first using an encoding such as Base64 so that json.dumps() will know how to serialize it:

import base64
post_data = {'image': base64.b64encode(img).decode()}

# Alternative conversion to text, but can be less space-efficient due to
# how non-ASCII characters are serialized in JSON - \uxxxx escapes:
post_data = {'image': img.decode('latin1')}

(also see the this question for more details)

Of course, subscribers will have to do just the opposite conversions to get back the binary image data from the received messages.

plamut
  • 3,085
  • 10
  • 29
  • 40