python protobuf can't deserialize message

|▌冷眼眸甩不掉的悲伤 提交于 2020-01-06 06:09:23

问题


Getting started with protobuf in python I face a strange issue:

a simple message proto definition is:

syntax = "proto3";
package test;

message Message {
  string message = 1;
  string sender = 2;
}

generated via protoc -I . --python_out=generated message.proto and accessed in Python like:

from generated.message_pb2 import Message

Then I can construct a message

m = Message()
m.sender = 'foo'
m.message = 'bar'

print(str(m))

but de-serializing will not return a result

s_m = m.SerializeToString()
print(s_m) # prints fine
a = m.ParseFromString(s_m)
a.foo #fails with error - no attributes deserialized

回答1:


Instead of

a = m.ParseFromString(s_m)
a.foo

do this

a = m.FromString(s_m)
print a.sender

alternatively you can do this

m2 = Message()
m2.ParseFromString(s_m)
print m2.sender

The difference is that FromString returns a new object deserialized from the string whereas ParseFromString parses the string and sets the fields on the object.



来源:https://stackoverflow.com/questions/46675090/python-protobuf-cant-deserialize-message

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