python - AppEngine/Python NDB 键顺序

标签 python google-app-engine google-cloud-datastore gae-sessions

我有一个有趣的问题,只有在升级我的代码以使用 NDB 后才会出现。

我正在使用 gae-sessions ,它将 session 到期时间编码为存储在数据库中的每个 session 的 key 。例如, key 将具有以下格式:1363968220_6ea52c936f16fc557c0c03a5f276a056,其中前 10 个字符表示 session 到期时间的时间戳(值 1363968220 编码为“2013-03-22 16:03:40”)。

在升级到 NDB 之前,删除过期 session 的代码可以正常工作。升级后,代码错误地删除了尚未过期的 session 。代码如下:

time_time = time.time()
now_str = unicode(int(time_time))
now_str_datetime = datetime.datetime.fromtimestamp(time_time) 
q = SessionModel.query(namespace='')
key = ndb.Key(SessionModel, now_str + u'\ufffd', namespace='')
logging.info("Deleting sessions with key values less than %s [%s]" % (key, now_str_datetime))
q.filter(SessionModel._key < key)
results = q.fetch(500, keys_only=True)
# This is for debugging purposes
for r_key in results:
    logging.warning("Deleting key %s" % (r_key))

这会产生以下输出:

Deleting sessions with key values less than Key('SessionModel', '1363362698\xef\xbf\xbd') [2013-03-15 15:51:38.767947]
Deleting key Key('SessionModel', '1363924467_e0240e38b4047ef821ac62e07466351b')

如果这些键被视为字符串(使用字符串排序/优先规则),那么被删除的键(从 1363924467 开始)应该被认为小于我们过滤的键(从 1363362698 开始),所以我对 NDB 中发生的事情感到困惑,这会导致它无法正常工作。

最佳答案

很难解释,根据文档

https://developers.google.com/appengine/docs/python/ndb/keyclass?hl=zh-tw

Keys support comparisons, for example key1 == key2 or key1 < key2. These operators compare application ID, namespace, and the full "ancestor path". They use the same ordering as the Datastore uses for queries when ordering by a key property or by key.

备忘单 https://docs.google.com/document/d/1AefylbadN456_Z7BZOpZEXDq8cR8LYu7QgI7bt5V0Iw/mobilebasic

和源代码。都表明使用应该没问题。 key 按顺序由 app_id、namesapce 和 key 对组成。 也许您可以尝试打印 (key.app(), key.namespace(), key.pairs()) 以查看详细信息。

https://code.google.com/p/appengine-ndb-experiment/source/browse/ndb/key.py

def __gt__(self, other):
    """Greater than ordering."""
    if not isinstance(other, Key):
      return NotImplemented
    return self.__tuple() > other.__tuple()

def __tuple(self):
    """Helper to return an orderable tuple."""
    return (self.app(), self.namespace(), self.pairs())

关于python - AppEngine/Python NDB 键顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15437320/

相关文章:

java - 如何在 GAE 中存储和检索 (_sh_SESSION) 值

python - 谷歌应用引擎: BadQueryError: Parse Error: Expected no additional symbols at symbol GROUP

google-app-engine - 提供来自自定义域、用户定义的 URL 和可选访问控制的缩略图

python - 如何使用 Python 的 timeit 为代码段计时以测试性能?

python - 如何在Python中比较两个不同.csv文件中的列?

python - Django 百分比表单域

google-app-engine - 从 gae 数据存储中选择不同的值并渲染 html

python - matplotlib 中的自定义绘图线型

python - Errno 10054 现有连接被远程主机强行关闭。 - 如何调试?

java - appengine Key.createKey(kind, id) 是否始终返回相同的结果?