简体   繁体   English

python protobuf为google proto的任何字段分配一个字典

[英]python protobuf assign a dictionary to any fields of google proto

I have a.prot file which consists of below fields user.proto我有一个.prot 文件,其中包含以下字段 user.proto

message Integration {
 string db_name = 1;
 oneof payload {
        Asset asset = 2;
        }
     }
message Asset {
 string address = 1;
 google.protobuf.Any extra_fields = 2;
 }

I just want to assign a large dictionary to extra_fields like below我只想为 extra_fields 分配一个大字典,如下所示

importing the generated pb2 file导入生成的 pb2 文件

import user_pb2
i = user_pb2.Integration()
i.db_name = "sdsdsd"
i.asset.address = "sdsd"
i.asset.extra_fields = {"assd":"sdsd","sd":"asd"...}

but it is raising the但它正在提高

AttributeError: Assignment not allowed to field "extra_fields" in the protocol message object.

I don't want to specify the filed names in proto because my dict contains over 100 fields I just want to assign total dict to extra fields can anyone suggest how to insert dict to extra fields?我不想在 proto 中指定字段名称,因为我的 dict 包含 100 多个字段 我只想将总 dict 分配给额外的字段 谁能建议如何将 dict 插入额外的字段?

You just need to skip .asset and assign i.address or i.extra_fields directly.你只需要跳过.asset并直接分配i.addressi.extra_fields For example:例如:

i.extra_fields = {"a": "b"}

see the documentation: https://developers.google.com/protocol-buffers/docs/reference/python-generated#oneof请参阅文档: https : //developers.google.com/protocol-buffers/docs/reference/python-generated#oneof

Finally, we figured out how to add the dict to protobuf directly, using struct keyword in google protobuf最后,我们想出了如何将dict直接添加到protobuf,使用google protobuf中的struct关键字

message Integration {
 string db_name = 1;
 oneof payload {
        Asset asset = 2;
        }
     }
message Asset {
 string address = 1;
google.protobuf.Struct extra_fields = 2;

 }

instead of any we used struct in the assigning, we can do directly update the dict而不是我们在分配中使用的任何结构,我们可以直接更新字典

import user_pb2
i = user_pb2.Integration()
i.db_name = "sdsdsd"
i.asset.address = "sdsd"
i.asset.extra_fields.update({"assd":"sdsd","sd":"asd"})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM