我想使用 Flask-Cache 来缓存不是 View 的函数的结果。但是,它似乎只有在我装饰 View 函数时才有效。 Flask-Cache 可以用来缓存“普通”函数吗?
如果我装饰一个 View 函数,缓存就会起作用。
cache = Cache(app,config={'CACHE_TYPE': 'simple'})
@app.route('/statistics/', methods=['GET'])
@cache.cached(timeout=500, key_prefix='stats')
def statistics():
return render_template('global/application.html') # caching works here
如果我修饰一个“普通”函数并从 View 中调用它,它就不起作用。
class Foo(object):
@cache.cached(timeout=10, key_prefix='filters1')
def simple_method(self):
a = 1
return a # caching NOT working here
@app.route('/statistics/filters/', methods=['GET'])
def statistics_filter():
Foo().simple_method()
如果我对这两个函数使用相同的 key_prefix
,它也会起作用。我认为这是缓存自身正在正确初始化的线索,但我调用简单方法或定义它的方式是错误的。
最佳答案
我认为您需要在 simple_method
中返回一些内容,以便 Flask-Cache 缓存返回值。我怀疑它是否会自己找出要缓存的方法中的哪个变量。
另一件事是你需要一个单独的函数来计算和缓存你的结果,如下所示:
def simple_method(self):
@cache.cached(timeout=10, key_prefix='filters1')
def compute_a():
return a = 1
return compute_a()
如果要缓存方法,使用memoize
关于python - 使用 Flask-Cache 缓存非 View 函数的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33020063/