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

后端 未结 2 1143
梦谈多话
梦谈多话 2021-01-03 00:15

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.ex         


        
相关标签:
2条回答
  • 2021-01-03 01:11

    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()
    
    0 讨论(0)
  • 2021-01-03 01:13
    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.

    0 讨论(0)
提交回复
热议问题