我希望使用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
,它也可以工作。我认为这是一个线索,说明缓存本身被正确初始化了,但我调用简单方法或定义它的方式可能有误。