db.model_from_protobuf()在AppEngine之外的等价物?

时间:2018-01-24 23:15:44

标签: google-app-engine google-cloud-platform google-cloud-datastore protocol-buffers google-compute-engine

在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`

问题:如果我只给出编码的字节字符串怎么办?如何将其转换回google.cloud.datastore.entity.Entity(或dict)?

Followups:

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

那就做到了..

1 个答案:

答案 0 :(得分:2)

这有效:

e = google.cloud.proto.datastore.v1.entity_pb2.Entity()
e.ParseFromString(byte_str)
print e