我想使用Flask-Cache来缓存不是视图的函数的结果。然而,它似乎只有在我装饰一个视图函数的情况下才能工作。Flask-Cache可以用来缓存“正常”函数吗?
如果我修饰一个视图函数,缓存就会起作用。
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如果我修饰一个“普通”函数并从视图中调用它,它就不会起作用。
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,它也可以工作。我认为这是缓存本身被正确初始化的一个线索,但我调用简单方法或定义它的方式是错误的。
发布于 2015-10-12 14:18:20
我认为你需要在你的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
https://stackoverflow.com/questions/33020063
复制相似问题