Protobuf不会序列化默认值

时间:2015-06-24 08:43:27

标签: python protocol-buffers

我正在使用Protobuf for python。

我一直在尝试使用默认值,但每次运行SerializeToString()时我什么都没得到。

例如,

这是我的.proto文件对象

message Test{

    optional string lol = 1 [default="HI"];
    optional int32 num = 2 [default=200];
}

我跑

test = packets_pb2.Test()
print(test.num)
print(test.SerializeToString())

得到 200用于打印(test.num) 但是SerializeToString()

没有结果(空)

我希望序列化我的默认值。

知道如何完成这项工作吗?

提前致谢。

2 个答案:

答案 0 :(得分:2)

This is working as intended. Default values are not sent on the wire. Instead, the receiving end assumes that if a field isn't present, then it should use the default value. This saves space on the wire by not sending common values. This does mean that the client and server have to agree on the default values; you generally should not change the default values in your .proto files. Keep in mind that the main purpose of default values is to be able to handle messages from old clients that were built before the field existed. So, those clients clearly can't send the default value on the wire since they don't know anything about it.

答案 1 :(得分:0)

对于使用Protobuf 3的任何人,都有一种方法可以使用including_default_value_fieldsMessageToJsonMessageToDict参数来序列化默认值:

from google.protobuf.json_format import MessageToJson

serialized_message_with_defaults = MessageToJson(
    protobuf_instance,
    including_default_value_fields=True,  # this does it
)