python - 使用 Flask-Cache 缓存非 View 函数的结果

标签 python caching flask flask-cache

我想使用 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/

相关文章:

python - 将 PostgreSQL 数据库与 Docker 和 Flask 结合使用,它是如何工作的?

python - 从字典列表中获取新列表

python - 使用 sympy 中给定的术语进行智能替换

python - 具有自定义浮点格式的 pprint

python - Django:我需要制定缓存方法吗?

python - 如何根据 flask 中的先前值检索第二个值

python - 如何随机化 if/elif 语句的顺序?

ruby-on-rails - ActiveRecord`includes'不将数据缓存在生产环境中

c# - 缓存页面的仅限管理员内容

python - Flask 从外部 API 函数重定向