Python Google应用程序引擎memcache.Client.cas()不断为缺少的密钥返回False
以下是在Google App Engine上运行的Python Flask应用程序的一部分:Python Google应用程序引擎memcache.Client.cas()不断为缺少的密钥返回False,python,google-app-engine,caching,google-app-engine-python,Python,Google App Engine,Caching,Google App Engine Python,以下是在Google App Engine上运行的Python Flask应用程序的一部分: @app.route('/blabla', methods=['GET']) def blabla(): # memcache.add('key', None) # this "fixes" it! memcache_client = memcache.Client() while True: value = memcache_client.gets('ke
@app.route('/blabla', methods=['GET'])
def blabla():
# memcache.add('key', None) # this "fixes" it!
memcache_client = memcache.Client()
while True:
value = memcache_client.gets('key')
if value is None: # First time
updated_value = 'Bla'
else:
updated_value = value + ', bla'
if memcache_client.cas('key', updated_value):
return updated_value
从空缓存开始,如果我们连续向/blabla发出GET请求,我希望请求返回:
Bla
Bla, bla
Bla, bla, bla
.
.
(如果由于某种原因,在.get()
和cas()
之间的某个点缓存被刷新,那么我希望序列能够重新启动,没有问题。)
但是我们什么也得不到,因为memcache\u client.cas()
总是返回False
,所以程序在的同时陷入循环。显然,这是因为键'key'
在开始时不存在
我之所以知道这一点,是因为如果我取消对memcache.add('key',None)
的注释,它就可以工作了,因为这样键就存在了,并且.cas()
很高兴并返回True
。但是如果正好在.add()
和.gets()
之间的某个其他进程要刷新缓存,我们将返回到开始的位置,缺少一个键,.cas()
将无限期返回False
。因此,这不是一个好的解决方案
如果一开始钥匙不见了,为什么.cas()
不起作用?或者至少,为什么.cas()
不接受初始值=
参数,就像它的兄弟一样?它是一个bug还是一个特性?我在任何地方都找不到适当的文档记录,除了Guido van Rossum在引用断言时提到它,他使.get()
不会返回无,他说:
旁白2:断言有点幼稚;实际上,您必须以某种方式处理计数器初始化
有人知道怎么做吗?好的,我知道了
@app.route('/blabla', methods=['GET'])
def blabla():
memcache_client = memcache.Client()
while True:
if memcache.add('key', 'Bla'):
# That's all folks!
return 'Bla'
# add() failed => the key must already exist, we have to compare-and-set.
value = memcache_client.gets(key_name)
if value is None:
# At the time add() failed the key existed, but now gets() is returning None,
# so somebody must have deleted the cache entry in between.
# Let's start from scratch.
continue
updated_value = value + ', bla'
if memcache_client.cas(key_name, updated_value):
return updated_value
else:
continue
这比我希望的要复杂,但它是有效的
最后一个else:continue
是多余的,但我写这篇文章是为了明确我们将继续努力,直到成功
尽管在实践中,你必须在多次尝试后以某种方式处理放弃