AttributeError: 'SimpleCache' object has no attribute 'has'

AttributeError: 'SimpleCache' object has no attribute 'has'

我从这段代码中得到以下错误:

def render(template, **kw):    
    if not cache.has("galleries"):
        cache.set('galleries', getTable(Gallery))
    return render_template(template, galleries=galleries, **kw)

错误:

File "/vagrant/diane/diane.py", line 38, in render
if cache.has("galleries"):
AttributeError: 'SimpleCache' object has no attribute 'has'

我以前多次使用相同的代码,没有任何问题。我也复制了这个和 运行 一个简单的测试并且它有效

from werkzeug.contrib.cache import SimpleCache
cache = SimpleCache()

def x():
    if cache.has('y'):
        print 'yes'
        print cache.get("y")
    else:
       print 'no'
x()

如有任何想法,我们将不胜感激。

从@JacobIRR 的评论中,从文档中可以清楚地看出它是一个可选字段。

文档是这样说的:

has(key) Checks if a key exists in the cache without returning it. This is a cheap operation that bypasses loading the actual data on the backend.

This method is optional and may not be implemented on all caches.

Parameters: key – the key to check

这里为了避免这种情况我们可以使用get(key)方法

get(key) Look up key in the cache and return the value for it.

Parameters: key – the key to be looked up. Returns: The value if it exists and is readable, else None. from werkzeug.contrib.cache import SimpleCache cache = SimpleCache()

下面是我们可以使用 get(key):

from werkzeug.contrib.cache import SimpleCache
cache = SimpleCache()

def x():
    if cache.get("y"): # if 'y' is not present it will return None.
        print 'yes'
    else:
       print 'no'
x()