由于我使用NDB为我的项目,在Python 2.7 SDK上,我不能正常使用Query().iter()与Jinja2模板。
我通常的代码遵循这个模式:
mc_key = ...
instances = memcache.get('instances-%s' % mc_key)
if not instances:
q_i = MyModel.query(...)
instances = q_i.iter()
if instances:
memcache.set('instances-%s' % mc_key, instances)
然后在Jinja2:
{% for i in instances %}
{{i.property1}}
{% endfor %}
当我在Python代码中调用QueryIterator对象时也会发生这种情况。添加到前面的Python代码:
for i in instances:
# Do something with i
当我循环迭代器时,我总是得到一个"deadlock waiting for
一个工作的遍历是:
q_i = MyModel.query()
instances = q_i.iter()
if instances:
instances = list(instances)
有人知道为什么next()不像我预期的那样工作吗?一些更优雅和/或更有效的解决方案?
您可以在文档中读到:NDB uses Memcache as a cache service for "hot spots" in the data. If the application reads some entities often, NDB can read them quickly from cache.
换句话说,缓存是自动的。
此外,获得实体列表的优雅方式是通过方法fetch()
instances = MyModel.query().fetch(20)
例如,本行中的instances
是一个包含20个实体的列表,并且该列表已经写入缓存。