python - 在 protobuf 中需要 `oneof`?

标签 python protocol-buffers

我想制作一个可以包含多种不同事件类型的 protobuf Event 消息。这是一个例子:

message Event {
    required int32 event_id = 1;

    oneof EventType {
        FooEvent foo_event = 2;
        BarEvent bar_event = 3;
        BazEvent baz_event = 4;
    }
}

这工作正常,但让我烦恼的一件事是 EventType 是可选的:我可以只用 event_id 编码一个对象,而 protobuf 不会提示。

>>> e = test_pb2.Event()
>>> e.IsInitialized()
False
>>> e.event_id = 1234
>>> e.IsInitialized()
True

有没有办法要求设置EventType?如果重要的话,我正在使用 Python。

最佳答案

根据 Protocol Buffers 文档,不推荐使用 required 字段规则,并且已在 proto3 中删除。

Required Is Forever You should be very careful about marking fields as required. If at some point you wish to stop writing or sending a required field, it will be problematic to change the field to an optional field – old readers will consider messages without this field to be incomplete and may reject or drop them unintentionally. You should consider writing application-specific custom validation routines for your buffers instead. Some engineers at Google have come to the conclusion that using required does more harm than good; they prefer to use only optional and repeated. However, this view is not universal.

正如上面的文档所说,您应该考虑使用特定于应用程序的验证,而不是将字段标记为必需

没有办法将 oneof 标记为“必需”(即使在 proto2 中),因为在引入 oneof 时,已经广泛接受字段可能永远不应该是“必需的”,因此设计者没有费心去实现一种方法来使 oneof 成为必需的。

关于python - 在 protobuf 中需要 `oneof`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42955621/

相关文章:

python - 如何在 Django Rest Framework 序列化程序中访问通过 POST 请求发送的额外数据

python - 烧杯无效CryptoBackendError : No AES library is installed error

python - flask 登录 : can't understand how it works from documentation

c# - Google Protocol Buffers - protobuf-net 反序列化无法正常工作

Python 结构模式匹配

python - BottlePy - 如何从钩子(Hook)中找到当前路线?

java - 谷歌 protobuf for Java 的“可选重复”

serialization - 原型(prototype)编译器(谷歌 Protocol Buffer )是用哪种语言编写的?

c# - 为什么在使用 java 和 protobuf-net 的 Protocol Buffer 进行序列化时 byte[] 不同?

java - 如何使用 protobuf 表示未命名的对象列表?