Protobuf doesn't serialize default values

不想你离开。 提交于 2019-12-22 17:44:24

问题


I'm using Protobuf for python.

I've been trying to use default values but everytime I run SerializeToString() i get nothing.

For example,

here is my .proto file object

message Test{

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

I run

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

and get 200 for print(test.num) but no results (empty) for SerializeToString()

I want my default values to be serialized.

Any idea how to get this done?

Thanks in advance.


回答1:


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.




回答2:


For anyone using Protobuf 3, there is a way to serialize the default values using the including_default_value_fields argument of MessageToDict or MessageToJson:

from google.protobuf.json_format import MessageToJson

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


来源:https://stackoverflow.com/questions/31021797/protobuf-doesnt-serialize-default-values

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