如何在Python protobuf中通过Fieldmask屏蔽地图字段?

时间:2018-11-20 08:58:45

标签: protocol-buffers

我想在Python中使用FieldMask屏蔽protobuf消息。

原始文件

syntax = "proto3";

message Msg {

    message ImageInfo {
        string url = 1;
        int32 width = 2;
        int32 height = 3;
    }

    string name = 1;
    map<string, ImageInfo> image_info = 2;
}

掩盖string字段可以成功完成。

from google.protobuf import field_mask_pb2
import msg_pb2

original_msg = msg_pb2.Msg(name='image-0')
original_msg.image_info['main'].url = 'http://example.com/image-0.jpg'
original_msg.image_info['main'].width = 10
original_msg.image_info['main'].height = 10

field_mask=field_mask_pb2.FieldMask(paths=['name'])
new_msg = msg_pb2.Msg()
field_mask.MergeMessage(original_msg, new_msg)

但是,屏蔽map<string, message>字段失败。

field_mask=field_mask_pb2.FieldMask(paths=['name', 'image_info'])
new_msg = msg_pb2.Msg()
field_mask.MergeMessage(original_msg, new_msg)

Traceback (most recent call last):   File "<stdin>", line 1, in <module>   File "/opt/project/test-1/lib/python3.7/site-packages/google/protobuf/internal/well_known_types.py", line 473, in MergeMessage
    source, destination, replace_message_field, replace_repeated_field)   File "/opt/project/test-1/lib/python3.7/site-packages/google/protobuf/internal/well_known_types.py", line 625, in MergeMessage
    self._root, source, destination, replace_message, replace_repeated)   File "/opt/project/test-1/lib/python3.7/site-packages/google/protobuf/internal/well_known_types.py", line 667, in _MergeMessage
    repeated_destination.add().MergeFrom(item) AttributeError: 'google.protobuf.pyext._message.MessageMapContainer' object has no attribute 'add'

如何遮盖它?

编辑

一种解决方案是包装消息。但这有点麻烦。

syntax = "proto3";

message Msg {

    message ImageInfo {
        string url = 1;
        int32 width = 2;
        int32 height = 3;
    }
    message ImageInfoContainer {
        map<string, ImageInfo> image_info = 1;
    }

    string name = 1;
    ImageInfoContainer image_info = 2;
}

0 个答案:

没有答案