Python 协议缓冲区字段选项 [英] Python Protocol Buffer field options

查看:64
本文介绍了Python 协议缓冲区字段选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获得与协议缓冲区字段关联的选项?

How does one get the options associated with a protocol buffer field?

例如,假设我有一个带有自定义选项的字段:

E.g., suppose I have a field with a custom options:

message Foo {
  optional string title = 1 [(indexed) = true];
}

我可以获得字段列表:

for f in foo.ListFields():
  print f

如何访问索引"状态?(我可以看到有一个 f "_options" 列表,但这似乎是内部"?有没有正确的方法可以按名称访问选项扩展)?

How do I access the "indexed" state? (I can see there is a list of f "_options", but that seems "internal"? Is there a proper way to access option extensions by name)?

推荐答案

我将使用定义的 nanopb 自定义选项作为示例 这里.然而,答案本身并不是特定于 nanopb 的,nanopb 使用标准的 protobuf 样式来自定义选项:

I'll use as an example the nanopb custom options, as defined here. However the answer itself is not in any way nanopb-specific, nanopb uses the standard protobuf style for custom options:

message NanoPBOptions {
   optional int32 max_size = 1;
   ...
}
extend google.protobuf.FieldOptions {
   optional NanoPBOptions nanopb = 1010;
}

和一个这样定义的选项:

and an option defined like this:

message Person {
   optional string email = 3 [(nanopb).max_size = 40];
}

用于获取选项值的 API 因语言而异.但是基本流程是一样的:

The API used to get the option value varies between languages. However the basic flow is the same:

  1. 从对象中获取消息描述符.
  2. 从消息描述符中获取字段描述符.
  3. 从字段描述符中获取选项.
  4. 从选项中获取扩展字段,以及您想要的值.

在 Python 中:

In Python:

desc = person_pb2.Person.DESCRIPTOR
field_desc = desc.fields_by_name['email']
options = field_desc.GetOptions()
value = options.Extensions[nanopb_pb2.nanopb].max_size

在 Java 中:

desc = PersonProto.Person.getDescriptor();
field_desc = desc.findFieldByName("email");
options = field_desc.getOptions();
value = options.getExtension(Nanopb.nanopb).getMaxSize();

在 C++ 中:

desc = Person::descriptor()
field_desc = desc->FindFieldByName("email");
options = field_desc->options();
value = options.GetExtension(nanopb).max_size());

这篇关于Python 协议缓冲区字段选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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