Google App Engine将db转换为ndb

时间:2013-01-22 05:59:32

标签: google-app-engine

在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,但我遇到了麻烦。

  1. 我还可以在HTML中使用'Advertisement.key'吗?

  2. ndb中没有db.get()方法。如何通过密钥检索实体?

1 个答案:

答案 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