【问题标题】:How to use a prototbuf map in Python?如何在 Python 中使用 protobuf 映射?
【发布时间】:2019-04-30 08:41:55
【问题描述】:

给定一个原型定义

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;
}

我希望在 EndpointResult 类中填充地图。我尝试了docs 中建议的不同方法,但都对我提出了错误。

设置测试类

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.

然后尝试不同的方法:

end_point_rslt.properties[0] = ts

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

end_point_rslt.properties[0].submessage_field = ts

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

end_point_rslt.properties.get_or_create(0)
end_point_rslt.properties[0] = ts

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

end_point_rslt.properties.get_or_create(0)
end_point_rslt.properties[0].submessage_field = ts

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

end_point_rslt.properties = {0 : ts}

AttributeError: 不允许对协议消息对象中的重复字段“属性”进行赋值。

end_point_rslt.properties.get_or_create(0)
end_point_rslt.properties = {0 : ts}

TypeError: 无法设置复合字段

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

【问题讨论】:

  • 感谢您的帖子。很高兴知道我不是唯一一个遭受痛苦的人
  • 体验很猫腻

标签: python protocol-buffers grpc


【解决方案1】:

查看文档后,我意识到问题在于我为字典分配了一个类。

正确的语法是

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.

【讨论】:

  • 如何动态添加键值到地图? Python protobuf 实现目前是个笑话!花了几个小时试图弄清楚简单的事情却发现它不起作用!
  • 这个帖子有解决办法:stackoverflow.com/questions/52583468/…
【解决方案2】:

Struct

的解决方法

代替

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

使用

message EndpointResult {
    int32 endpoint_id = 1;
    // property id as key
    google.protobuf.Struct properties = 2;
}

使用

发起消息
properties = google.protobuf.struct_pb2.Struct()
properties[key1]=[TimeEntry(time_unit1, val1), TimeEntry(time_unit2, val2)...]
properties[key2]=[TimeEntry(time_unit3, val3)...]

EndpointResult(
    endpoint_id='1',
    properties=properties
)

我也遇到过很多使用地图的问题,发现这个解决方案有效

【讨论】:

    猜你喜欢
    • 2018-06-25
    • 2016-07-23
    • 2020-11-21
    • 1970-01-01
    • 2018-10-05
    • 2018-12-27
    • 1970-01-01
    • 2021-11-11
    • 1970-01-01
    相关资源
    最近更新 更多