python - 如何在 Python 中使用 protobuf 映射?

标签 python protocol-buffers grpc

给定一个原型(prototype)定义

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 类中填充 map 。我尝试了 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: Direct assignment of submessage not allowed

end_point_rslt.properties[0].submessage_field = ts

AttributeError: Assignment not allowed (no field "submessage_field" in protocol message object).

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

ValueError: Direct assignment of submessage not allowed

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

AttributeError: Assignment not allowed (no field "submessage_field" in protocol message object).

end_point_rslt.properties = {0 : ts}

AttributeError: Assignment not allowed to repeated field "properties" in protocol message object.

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

TypeError: Can't set composite field

任何关于如何在 python 中使用 Protocol Buffer 映射的示例将不胜感激!

最佳答案

看了文档之后,我意识到问题出在我给字典分配了一个类。

正确的语法是

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 - 如何在 Python 中使用 protobuf 映射?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53519472/

相关文章:

javascript - Python - 如何找到圆的 x 和 y 坐标以在 map 上创建圆弧

python-2.7 - python protobuf 安装为 windows

matlab - 如何让 Google Protobuf 在 Matlab 中工作?

c++ - 使用 std::iterator 的 gRPC auth_context.h 使用最新的 VC++ 编译器产生不推荐使用的警告

rest - GRPC 重复字段不会转码为数组作为 REST API 中的正文参数

python - 文件夹上的备用数据流

python - 如何将一个 python 字典附加到另一个,同时保留它们的键值?

python - 将 groupby-apply 结果分配给父数据框

java - 如何导入内部protobuf消息?

go - 在 Golang 中设置网络命名空间后运行 GRPC 是否有任何已知限制?