将NDB安全URL键字符串转换为googledatastore.Key

0 投票
3 回答
1110 浏览
提问于 2025-04-18 15:27

我想要能够在 ndb.key.urlsafe() 字符串和 googledatastore python库 之间共享数据。

  • 有没有人能给个例子,教我怎么从 ndb.key.urlsafe() 字符串构建一个 googledatastore.Key
  • 另外,如果能给个例子,教我怎么从 googledatastore.Key 创建一个 urlsafe 字符串,那就更好了。

我还在 GitHub上提了个问题

编辑:注意,googledatastore 有 SerializeToString() 和 FromString() 方法,但它们是基于 protobuff 的,不接受 ndb 的键字符串。

3 个回答

1

那 nd.to_old_key() 呢?这不正是你想要的东西吗?

https://developers.google.com/appengine/docs/python/ndb/keyclass#Key_urlsafe

1

你可能需要自己动手做一些工作,因为Cloud Datastore和ndb使用的格式不一样。ndb的urlsafe是它自己的一个功能(它是基于base64编码加上一些格式化的东西),我建议你先用ndb来读取这个urlsafe格式,然后再把它转换成Cloud Datastore的键:

urlsafeKey = '....'
# First, let ndb deserialize the key.
ndbKey = ndb.Key(urlsafe=urlsafeKey)
# Rebuild the Cloud Datastore key using the path from ndb.
cloudKey = googledatastore.datastore_v1_pb2.Key()
for pair in ndbKey.pairs():
  googledatastore.helper.add_key_path(cloudKey, pair[0], pair[1])

如果你想把一个googledatastore的键转换成ndb序列化的键,你可以反过来做同样的事情。

pairs = []
for path_element in cloudKey.path_elements:
  if path_element.HasField('name'):
    id_or_name = path_element.name
  else:
    id_or_name = path_element.id
  pairs.append((path_element.kind, id_or_name))
ndbKey = ndb.Key(pairs=pairs)

免责声明: 我并没有实际运行这些代码,所以你可能需要稍微调整一下。

0

我请同事从appengine库中提取了一些代码。结果是这样的:https://github.com/transceptor-technology/dbWrapper/blob/master/gcdKeyNdbKey.py

它提供了以下功能: from gcdKeyNdbKey import gcdKeyFromUrlSafe from gcdKeyNdbKey import urlSafeFromGcdKey

撰写回答