views:

117

answers:

2

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.

A: 

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()
David Underhill
+4  A: 
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.

Alex Martelli
Lack of documentation of .to_path() is a bug - it's definitely intended to be used externally. :)
Nick Johnson
It is certainly a lot easier than trying to manually decode it!
David Underhill
@Nick, I suspected that, but didn't really _know_! So, tx for the info. Fortunately, it looks like it's just going to be a fast-to-fix documentation bug.
Alex Martelli
Setup I used to test: export PYTHONPATH=/usr/local/share/google_appengine/:/usr/local/share/google_appengine/lib/yaml/lib (because I installed into /usr/local/share)
dfrankow