繁体   English   中英

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

[英]python protobuf assign a dictionary to any fields of google 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;
 }

我只想为 extra_fields 分配一个大字典,如下所示

导入生成的 pb2 文件

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

但它正在提高

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

我不想在 proto 中指定字段名称,因为我的 dict 包含 100 多个字段 我只想将总 dict 分配给额外的字段 谁能建议如何将 dict 插入额外的字段?

你只需要跳过.asset并直接分配i.addressi.extra_fields 例如:

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

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

最后,我们想出了如何将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;

 }

而不是我们在分配中使用的任何结构,我们可以直接更新字典

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