Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 669
dfrankow Avatar asked Jun 30 '10 16:06

dfrankow


2 Answers

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.

like image 70
Alex Martelli Avatar answered Nov 11 '22 19:11

Alex Martelli


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()
like image 33
David Underhill Avatar answered Nov 11 '22 20:11

David Underhill