首页 > 解决方案 > python protobuf 将字典分配给 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 插入额外的字段吗?

标签: pythonpython-3.xprotoprotobuf-3

解决方案


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

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

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


推荐阅读