简体   繁体   中英

How to use Value in the python implementation of protobuf

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())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM