在 Google AppEngine(GAE) 环境中,我可以执行以下操作将 Protobuf 字节串转换回数据存储模型:
from google.appengine.ext import db
byte_str = ....
model = db.model_from_protobuf(byte_str.decode("base64"))
在 GAE 之外,我通常使用google-cloud-datastore
客户端访问数据存储模型:
from google.cloud import datastore
...
client = datastore.Client(project_id)
query = client.query(kind='Event', order=('-date',))
for result in query.fetch(limit=100):
print result
# every result is of class `google.cloud.datastore.entity.Entity`
Question:如果我只得到编码的字节字符串怎么办?我怎样才能将它转换回google.cloud.datastore.entity.Entity
(or dict
)?
后续行动:
Update1:
google.cloud.proto.datastore.v1.entity_pb2.Entity.ParseFromString()
是迄今为止我发现的最接近的。但还没有完全工作..
## fetched a protobuf into `pb`
>>> pb.__class__
<class 'google.cloud.proto.datastore.v1.entity_pb2.Entity'>
>>> entity = google.cloud.datastore.helpers.entity_from_protobuf(pb)
>>> entity.__class__
<class 'google.cloud.datastore.entity.Entity'>
>>> serialized = pb.SerializeToString() ## <-- now this is the bytestring I meant.
>>> type(serialized)
<type 'str'>
>>> google.cloud.proto.datastore.v1.entity_pb2.Entity.ParseFromString(serialized)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: descriptor 'ParseFromString' requires a 'google.protobuf.pyext._message.CMessage' object but received a 'str'
>>>google.cloud.proto.datastore.v1.entity_pb2.Entity().ParseFromString(serialized)
76942 ## <--??
Update2:
实际上必须这样做:
e = google.cloud.proto.datastore.v1.entity_pb2.Entity()
e.ParseFromString(byte_str)
print e
就这样做到了..