简体   繁体   中英

How to decode a Google App Engine entity Key path str in Python?

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.

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.

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM