如何在 Python 中使用 prototbuf 映射?

Edg*_*r H 12 python protocol-buffers grpc

给定一个原型定义

message EndpointResult {
    int32 endpoint_id = 1;
    // property id as key
    map<int32, TimeSeries> properties = 2;
}

message TimeSeries {
    repeated TimeEntry value = 2;
}

message TimeEntry {
    int32 time_unit = 1;
    float value = 2;
}
Run Code Online (Sandbox Code Playgroud)

我希望在 EndpointResult 类中填充地图。我尝试了文档中建议的不同方法,但都给我带来了错误。

设置测试类

end_point_rslt = nom.EndpointResult()
end_point_rslt.endpoint_id=0

ts = nom.TimeSeries()
te = ts.value.add()
te.time_unit = 0
te.value = 5.
Run Code Online (Sandbox Code Playgroud)

然后尝试不同的方法:

end_point_rslt.properties[0] = ts
Run Code Online (Sandbox Code Playgroud)

ValueError:不允许直接分配子消息

end_point_rslt.properties[0].submessage_field = ts
Run Code Online (Sandbox Code Playgroud)

AttributeError:不允许分配(协议消息对象中没有字段“submessage_field”)。

end_point_rslt.properties.get_or_create(0)
end_point_rslt.properties[0] = ts
Run Code Online (Sandbox Code Playgroud)

ValueError:不允许直接分配子消息

end_point_rslt.properties.get_or_create(0)
end_point_rslt.properties[0].submessage_field = ts
Run Code Online (Sandbox Code Playgroud)

AttributeError:不允许分配(协议消息对象中没有字段“submessage_field”)。

end_point_rslt.properties = {0 : ts}
Run Code Online (Sandbox Code Playgroud)

AttributeError:不允许分配给协议消息对象中的重复字段“属性”。

end_point_rslt.properties.get_or_create(0)
end_point_rslt.properties = {0 : ts}
Run Code Online (Sandbox Code Playgroud)

类型错误:无法设置复合字段

任何有关如何在 python 中使用协议缓冲区映射的示例将不胜感激!

Edg*_*r H 7

盯着文档后,我意识到问题是我给字典分配了一个类。

正确的语法是

end_point_rslt = nom.EndpointResult()
end_point_rslt.endpoint_id=0
te = end_point_rslt.properties[0].value.add()
te.time_unit = 0
te.value = 5.
Run Code Online (Sandbox Code Playgroud)

  • 如何动态添加键值到地图?Python protobuf 实现目前是一个笑话!花了几个小时试图解决简单的问题却发现它不起作用! (3认同)