user3084959 user3084959 - 4 months ago 27
Python Question

Retrieve key from automatically assigned ID which has been passed through URL in GAE, using ndb and python

I've been struggling with this for hours and tried everything!

So basically

I have a class called City:

class City(ndb.Model):
_parent = None
city = ndb.StringProperty(required=True)
created = ndb.DateTimeProperty(auto_now_add=True)

When i make a new city, it is given an automatic ID, such as 6438740092256256

Later on i want to add a Restaurant entity to this city as a child. So I have passed the city ID in the url, like this:

which leads to this bit of code

class PostRestaurant(webapp2.RequestHandler):
def post(self, resource):
key = ????

where resource is 6438740092256256

What i want to do is to be able to retrieve the key using the 6438740092256256 from the url. However every single approach i have tried results in an unknown error.

Ive tried everything, including key = :


ndb.Key(City, resource).get()

ndb.Key('City', int(resource))


pnv pnv

You are getting urlsafe string here.

this_key = ndb.Key(urlsafe=resource)
query_result_as_entity = this_key.get()

After converting urlsafe string to key, you can just do get() on it.