How to fetch the latest data in GAE Python NDB

半世苍凉 提交于 2019-12-04 17:25:58

There's a couple ways on app engine to get strong consistency, most commonly using gets instead of queries and using ancestor queries.

To use a get in your example, you could encode the name into the entity key:

class Y(ndb.Model):
  result = ndb.StructuredProperty(X, repeated=True)

def put(name, result):
  Y(key=ndb.Key(Y, name), result).put()

def get_records(name):
  record_list = ndb.Key(Y, name).get()
  return record_list

An ancestor query uses similar concepts to do something more powerful. For example, fetching the latest record with a specific name:

import time

class Y(ndb.Model):
  result = ndb.StructuredProperty(X, repeated=True)

  @classmethod
  def put_result(cls, name, result):
    # Don't use integers for last field in key. (one weird trick)
    key = ndb.Key('name', name, cls, str(int(time.time())))
    cls(key=key, result=result).put()

  @classmethod
  def get_latest_result(cls, name):
    qry = cls.query(ancestor=ndb.Key('name', name)).order(-cls.key)
    latest = qry.fetch(1)
    if latest:
      return latest[0]

The "ancestor" is the first pair of the entity's key. As long as you can put a key with at least the first pair into the query, you'll get strong consistency.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!