Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serialize an entity key to a string in Python for GAE

In the Java low-level API, there is a way to turn an entity key into a string so you can pass it around to a client via JSON if you want. Is there a way to do this for python?

like image 956
Chris Dutrow Avatar asked Apr 28 '11 20:04

Chris Dutrow


4 Answers

Depending on whether you use keynames or not, obj.key().name() or obj.key().id() can be used to retrieve keyname or ID, respectively. Neither of those contain name of the entity class so they are not sufficient to retrieve the original object from datastore. Granted, in most cases you usually know the entity kind when working with it, so that not a problem.

A universal solution, working in both cases (keynames or not) is obj.key().id_or_name(). This way you can retrieve the original object as follows:

from google.appengine.ext import db
#...
obj_key = db.Key.from_path('EntityClass', id_or_name)
obj = db.get(obj_key)

If you don't mind passing the long, cryptic string that also containts some extra data (like name of your GAE app), you can use the string representation of the key (str(obj.key()) and pass it directly to db.get for retrieving the object.

like image 176
Xion Avatar answered Oct 29 '22 04:10

Xion


str(entity.key()) will return a base64-encoded representation of the key.

entity.key().name() or entity.key().id() will return just the name or ID, omitting the kind and the ancestry.

like image 31
Drew Sears Avatar answered Oct 29 '22 04:10

Drew Sears


better:

string_key = entity.key().urlsafe()

and after you can decode de key with

key = ndb.Key(urlsafe=string_key)
like image 28
user3444814 Avatar answered Oct 29 '22 04:10

user3444814


You should be able to do:

entity.key().name()

This should return the string representation of the key. See here

Is that what you're looking for?

like image 1
oli Avatar answered Oct 29 '22 06:10

oli