【问题标题】:python protobuf assign a dictionary to any fields of google protopython protobuf 将字典分配给 google proto 的任何字段
【发布时间】:2020-03-23 06:47:42
【问题描述】:

我有一个包含以下字段的.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 插入额外的字段?

【问题讨论】:

    标签: python python-3.x proto protobuf-3


    【解决方案1】:

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

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

    查看文档:https://developers.google.com/protocol-buffers/docs/reference/python-generated#oneof

    【讨论】:

    • 它没有直接价值@acrazing
    【解决方案2】:

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

    而不是我们使用的任何结构 在分配中,我们可以直接更新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"})
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-19
      • 1970-01-01
      • 2021-12-27
      • 1970-01-01
      • 2017-11-07
      • 1970-01-01
      • 1970-01-01
      • 2012-11-05
      相关资源
      最近更新 更多