Protobuf 不会序列化默认值 [英] Protobuf doesn't serialize default values

查看:92
本文介绍了Protobuf 不会序列化默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Python 中使用 Protobuf.

I'm using Protobuf for python.

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

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

例如

这是我的 .proto 文件对象

here is my .proto file object

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() 没有结果(空)

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?

提前致谢.

推荐答案

这是按预期工作的.默认值不在线路上发送.相反,接收端假定如果一个字段不存在,那么它应该使用默认值.这通过不发送公共值来节省线路上的空间.这确实意味着客户端和服务器必须就默认值达成一致;您通常不应更改 .proto 文件中的默认值.

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.

这篇关于Protobuf 不会序列化默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆