4

How to read Protobuf message through bytearray response as string?

I tried looking up Protobuf library. https://developers.google.com/protocol-buffers/docs/reference/python/google.protobuf.message-pysrc#Message.MergeFrom

When I tried mergeFrom , mergeFromString to fetch response back. I am getting below error.

TypeError: Parameter to MergeFrom() must be instance of same class: expected GetUpdateResponseMsg got bytes.

I tried ParseFromString api and got None response back.

I am trying to deserialize Protobuf back to human readable format.

Is there anything else I can try?

nevihs
  • 991
  • 1
  • 12
  • 23

1 Answers1

4

You need to deserialize the response. Pass in the class/protobuf type along with message and you should get the response in the format.. Sample example would be:

from BusinessLayer.py.GetDealUpdateData_pb2 import GetDealUpdateResponseDM
from importlib import import_module
def deserialize(byte_message, proto_type):
    module_, class_ = proto_type.rsplit('.', 1)
    class_ = getattr(import_module(module_), class_)
    rv = class_()
    rv.ParseFromString(byte_message)
    return rv

print (deserialize(byte_message, 'BusinessLayer.py.GetDealUpdateData_pb2.GetDealUpdateResponseDM'))

byte_message is message which you will get as response.

Let me know if you have any questions.

  • Hi @Anand this method is not working for me and giving me error 'Field number 0 is illegal' . In java there is a method to parse bytearray 'fromByteArray; I am unable to find a similar method in python. Could you please help? – user812142 Sep 24 '20 at 18:07