How to decode a Google App Engine entity Key path

2019-02-10 04:33发布

In Google App Engine, an entity has a Key. A key can be made from a path, in which case str(key) is an opaque hex string. Example:

from google.appengine.ext import db
foo = db.Key.from_path(u'foo', u'bar', _app=u'baz')
print foo

gives

agNiYXpyDAsSA2ZvbyIDYmFyDA

if you set up the right paths to run the code.

So, how can one take the hex string and get the path back? I thought the answer would be in Key or entity group docs, but I can't see it.

2条回答
倾城 Initia
2楼-- · 2019-02-10 05:01

Once you have the Key object (which can be created by passing that opaque identifier to the constructor), use Key.to_path() to get the path of a Key as a list. For example:

from google.appengine.ext import db
opaque_id = 'agNiYXpyDAsSA2ZvbyIDYmFyDA'
path = db.Key(opaque_id).to_path()
查看更多
萌系小妹纸
3楼-- · 2019-02-10 05:02
from google.appengine.ext import db

k = db.Key('agNiYXpyDAsSA2ZvbyIDYmFyDA')
_app = k.app()
path = []
while k is not None:
  path.append(k.id_or_name())
  path.append(k.kind())
  k = k.parent()
path.reverse()
print 'app=%r, path=%r' % (_app, path)

when run in a Development Console, this outputs:

app=u'baz', path=[u'foo', u'bar']

as requested. A shorter alternative is to use the (unfortunately, I believe, undocumented) to_path method of Key instances:

k = db.Key('agNiYXpyDAsSA2ZvbyIDYmFyDA')
_app = k.app()
path = k.to_path()
print 'app=%r, path=%r' % (_app, path)

with the same results. But the first, longer version relies only on documented methods.

查看更多
登录 后发表回答