nevihs
nevihs

Reputation: 1051

Deserialize Protobuf 3 bytearray in python

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?

Upvotes: 4

Views: 7121

Answers (1)

Anand Kumar
Anand Kumar

Reputation: 56

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.

Upvotes: 4

Related Questions