I have a proto file defined as:
syntax = "proto3";
import "google/protobuf/struct.proto";
package generic.name;
message Message {
uint32 increment = 1;
google.protobuf.Value payload = 2;
}
I have figured out how to make this work if I swap the payload type from Value for Struct:
struct = Struct()
struct.update({"a": 1})
msg = Message(payload=struct, increment=1)
However I cannot work out how to use the Value type in python. The python documentation for the protobuf Value field seems lacking compared to the other languages. Ultimately, all I want is to be able to have the payload data structure able to take a few different types (strings, ints, none, dict). What is the best way of achieving this?
Here's an example:
from foo_pb2 import Bar
from google.protobuf.struct_pb2 import Struct
bar = Bar()
bar.payload.string_value="Freddie"
print(bar)
print(bar.SerializeToString())
bar.payload.bool_value=True
print(bar)
print(bar.SerializeToString())
# No need to initialize the Struct
bar.payload.struct_value.update({"foo":"bar"})
bar.payload.struct_value["baz"]=5
print(bar)
print(bar.SerializeToString())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With