Deserialize Protobuf 3 bytearray in python

你说的曾经没有我的故事 提交于 2019-12-21 20:29:43

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/44946492/deserialize-protobuf-3-bytearray-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!