【问题标题】:Use Flask-Cache to cache result of non-view function使用 Flask-Cache 缓存非视图函数的结果
【发布时间】:2016-01-06 07:52:09
【问题描述】:

我想使用 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,它也可以工作。我认为这是一个线索,表明它自己的缓存正在正确初始化,但我调用简单方法或定义它的方式是错误的。

【问题讨论】:

标签: python caching flask flask-cache


【解决方案1】:

我认为您需要在 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

【讨论】:

  • 感谢@user1537085 的回答,返回了一个值但仍然没有缓存
猜你喜欢
  • 2014-01-20
  • 1970-01-01
  • 1970-01-01
  • 2020-03-20
  • 2010-11-13
  • 1970-01-01
  • 2016-07-10
  • 2011-01-14
相关资源
最近更新 更多