GAE Python NDB .put 在开发中不同步(但在生产中有效)? [英] GAE Python NDB .put not synchronous on development (but works in production)?

查看:27
本文介绍了GAE Python NDB .put 在开发中不同步(但在生产中有效)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面应该创建一个 Counter 模型并使用(延迟)任务将计数器增加到 10.访问 '/' 应该创建一个 Counter 对象,count = 10.这发生在生产中.在开发中(本地主机)创建了多个 Counter 对象,最大为 10:

The following below should create a Counter model and use (deferred) tasks to increment the counter to 10. Visiting '/' ought to create a single Counter object with count = 10. This happens in production. In development (localhost) multiple Counter objects are created with the largest being 10:

我怀疑这是因为 put 在开发中不是同步的(但似乎总是在生产中).有没有办法让它们同步?

I suspect this is because the put is not synchronous on development (but appears to always be on production). Is there a way to make them synchronous?

下面的代码片段:

class Counter(ndb.Model):
  count = ndb.IntegerProperty(indexed=False)

def reset():
  ndb.delete_multi(Counter().query().fetch(keys_only=True, use_cache=False, use_memcache=False))

def increment():
  counter = Counter().query().get(use_cache=False, use_memcache=False)
  if not counter:
    counter = Counter(count=0)

  counter.count += 1
  counter.put()

  if counter.count < 10:
    deferred.defer(increment)

@app.route('/')
def hello():
  """Return a friendly HTTP greeting."""
  reset()
  deferred.defer(increment)
  return 'Hello World!'

我有一个 git 存储库,可以在 此处 重现此行为.您可以在此处找到进行最后一次更改的提交.

I have a git repo that reproduces this behavior here. You can find the commit that makes the last change here.

推荐答案

生产同步性"只是显而易见的,不能保证(在您的方法中).总是有可能在查询中找不到新创建的计数器,因此您的代码可能会创建多个计数器.

The production 'synchronicity' is just apparent, it's not guaranteed (in your approach). It can always happen that a newly created counter is not found in the query, thus your code could create multiple counters.

使用 Google Cloud Datastore 平衡强一致性和最终一致性文章.

这篇关于GAE Python NDB .put 在开发中不同步(但在生产中有效)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆