Search code examples
pythonwerkzeug

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


I get the following error from this code:

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

Error:

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

I have used the same code several times before without any issue. I also copied this and ran a simple test and it works

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

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

Any ideas at all would be really appreciated.


Solution

  • From the comment of @JacobIRR, from doc it is clear that its a optional field.

    The docs says as follows:

    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

    Here to avoid this we can use get(key) method

    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()

    Here is what we can do by using 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()