On Google App Engine, I used to store images in db:
class Images(db.Model):
image = db.BlobProperty()
After inserting an entity (say, ‘advertisement’), I can use the following to render an image in an HTML page:
<img src="/image?entity_id={{advertisement.key}}" class="advertise" /></a><br />
At the server side, the image is retrieved by:
class GetImage(webapp2.RequestHandler):
def get(self):
entity_id = self.request.get('entity_id')
entity = db.get(entity_id)
if entity and entity.image:
self.response.headers['Content-Type'] = 'image/png'
self.response.out.write(entity.image)
And now, I would like to convert the datastore to ndb, but I am having troubles.
-
Can I still use ‘Advertisement.key’ in the HTML?
-
There is no db.get() method in ndb. How do I retrieve an entity by its key?
You can use ndb.Key.to_old_key()
https://developers.google.com/appengine/docs/python/ndb/keyclass#Key_to_old_key
to retrieve ndb entities use key.urlsafe:
https://developers.google.com/appengine/docs/python/ndb/keyclass#Key_urlsafe