在Google App Engine上,我曾经在db:
中存储图像class Images(db.Model):
image = db.BlobProperty()
插入实体(比如'广告')后,我可以使用以下内容在HTML页面中呈现图像:
<img src="/image?entity_id={{advertisement.key}}" class="advertise" /></a><br />
在服务器端,图像通过以下方式检索:
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)
现在,我想将数据存储区转换为ndb,但我遇到了麻烦。
我还可以在HTML中使用'Advertisement.key'吗?
ndb中没有db.get()方法。如何通过密钥检索实体?
答案 0 :(得分:1)
您可以使用ndb.Key.to_old_key()
https://developers.google.com/appengine/docs/python/ndb/keyclass#Key_to_old_key
<img src="/image?entity_id={{advertisement.key.to_old_key()}}" class="advertise" />
使用key.urlsafe:
检索ndb实体class Images(ndb.Model):
image = ndb.BlobProperty()
<img src="/image?entity_id={{advertisement.key.urlsafe()}}" class="advertise" /></a><br />
class GetImage(webapp2.RequestHandler):
def get(self):
entity_id = self.request.get('entity_id')
entity = ndb.Key(urlsafe=entity_id).get()
if entity and entity.image:
self.response.headers['Content-Type'] = 'image/png'
self.response.out.write(entity.image)
https://developers.google.com/appengine/docs/python/ndb/keyclass#Key_urlsafe