Reputation: 141
I have a.prot file which consists of below fields 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
importing the generated pb2 file
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?
Upvotes: 0
Views: 4221
Reputation: 141
Finally, we figured out how to add the dict to protobuf directly, using struct keyword in google protobuf
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"})
Upvotes: 0
Reputation: 2284
You just need to skip .asset
and assign i.address
or i.extra_fields
directly. For example:
i.extra_fields = {"a": "b"}
see the documentation: https://developers.google.com/protocol-buffers/docs/reference/python-generated#oneof
Upvotes: 0