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

后端 未结 2 1144
梦谈多话
梦谈多话 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: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.

提交回复
热议问题