In some cases, calling App Engine "get_by_key_name" using an existing keyname will return None

I ran into a weird issue that I hadn't seen before calling get_by_key_name

using the App Engine ORM.

Under no circumstances would it be possible to assume if the following would return None:

Model.get_by_key_name(Model.all().get().key().name())

      

And yet, this is what I found that some of the key names would do. This is only in a few cases where I use Open ID URLs such as the following key_name attributes:

https://me.yahoo.com/a/jadjuh3s0klsghiLhtBNbIiHw8k-#3dcl3

      

(I changed a couple of symbols to protect the innocent)

Maybe the "#" character?

Decision. As Nick Johnson suggested, I needed to change the query since the object has a parent:

entity = Model.all().get()
Model.get_by_key_name(entity.key().name(), parent=entity.parent_key())

      

In any case, if there are circumstances where the key name cannot be used to retrieve the entity, then it should not be allowed to be used as the key name in the first place.

+2


source to share


2 answers


Model.get_by_key_name (Model.all (). Get (). Key (). Name ()) will fail if the object returned by the query is a child of some other object. get_by_key_name with no parent parameter looks for an object without parents, while the query may return a child object.

For example:



a = Model1()
a.put()
b = Model2(parent=a)
b.put()
Model2.get_by_key_name(Model2.all().get().key().name()) # Fails to return anything
Model2.get(Model2.all().get().key()) # Works as expected

      

+4


source


out of curiosity, do you see this in production or in sdk or both?

I tried to reproduce it with your key name at http://shell.appspot.com/ but couldn't:



>>> class Foo(db.Expando):
  pass
>>> Foo(key_name='https://me.yahoo.com/a/jadjuh3s0klsghiLhtBNbIiHw8k-#3dcl3').put()
datastore_types.Key.from_path(u'Foo', u'https://me.yahoo.com/a/jadjuh3s0klsghiLhtBNbIiHw8k-#3dcl3', _app_id_namespace=u'shell')
>>> Foo.get_by_key_name('https://me.yahoo.com/a/jadjuh3s0klsghiLhtBNbIiHw8k-#3dcl3')
<__main__.Foo object at 0x75f9c1aa9181d78>

      

(Granted, I'm not using your model class hierarchy as you implied, maybe that's what gets it running.)

0


source







All Articles