AttributeError:“SimpleCache”对象没有“has”属性

2024-04-29 16:30:17 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

错误:

^{pr2}$

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

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

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

任何想法都会很感激的。在


Tags: 代码cacheifdef错误nottemplaterender
1条回答
网友
1楼 · 发布于 2024-04-29 16:30:17

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

文件内容如下:

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

相关问题 更多 >