Python pb3序列化使用pb3

Python pb3 serialization using pb3

我正在使用 pb3 进行序列化:

syntax = "proto3";

package marshalling;

import "google/protobuf/timestamp.proto";

message PrimitiveType {
  oneof primitive_value {
    bool boolean_value = 1;
    int64 int_value = 2;
    double double_value = 3;
    google.protobuf.Timestamp timestamp_value = 4;
  }
}

我生成了一个 x_pb2.py 文件,但不知道如何使用它。

例如,如果我想将时间戳编组为字节,我该怎么做?

参考The Protocol Buffer API部分:

Unlike when you generate Java and C++ protocol buffer code, the Python protocol buffer compiler doesn't generate your data access code for you directly. Instead, it generates special descriptors for all your messages, enums, and fields, and some mysteriously empty classes, one for each message type...

并且,

At load time, the GeneratedProtocolMessageType metaclass uses the specified descriptors to create all the Python methods you need to work with each message type and adds them to the relevant classes. You can then use the fully-populated classes in your code.

因此,您可以使用生成的 class(s) 创建对象及其字段,如下所示:

p1 = primitive_types_pb2.PrimitiveType()
p1.int_value = 1234

对于您的用例,您可以使用 timestamp_pb2.Timestamp.GetCurrentTime()

或者,您可以参考Timestamp along with timestamp_pb2.Timestamp.CopyFrom():

now = time.time()
seconds = int(now)
nanos = int((now - seconds) * 10**9)
timestamp = Timestamp(seconds=seconds, nanos=nanos)

p1 = primitive_types_pb2.PrimitiveType()
p1.timestamp_value.CopyFrom( timestamp )

还有其他 google.protobuf.timestamp_pb2 API,您可能会对其他用例感兴趣。


这是一个完整的工作示例 (primitive_types.proto):

import time  # For Timestamp.CopyFrom(). See commented code below
import primitive_types_pb2
from google.protobuf import timestamp_pb2

# serialization

p1 = primitive_types_pb2.PrimitiveType()

# Alternative to GetCurrentTime()
# now = time.time()
# seconds = int( now )
# nanos = int( (now - seconds) * 10**9 )
# timestamp = timestamp_pb2.Timestamp( seconds=seconds, nanos=nanos )
# p1.timestamp_value.CopyFrom( timestamp )

p1.timestamp_value.GetCurrentTime()

serialized = p1.SerializeToString()

# deserialization

p2 = primitive_types_pb2.PrimitiveType()
p2.ParseFromString( serialized )

print( p2.timestamp_value )

输出:

seconds: 1590581054
nanos: 648958000

参考文献: