简体   繁体   中英

Use Flask-Cache to cache result of non-view function

I want to use Flask-Cache to cache the result of a function that's not a view. However, it only seems to work if I decorate a view function. Can Flask-Cache be used to cache "normal" functions?

Caching works if I decorate a view function.

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

It doesn't work if I decorate a "normal" function and call it from a 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()

It also works if I use the same key_prefix for both functions. I think that's a clue that the cache it self is being initialized correctly but the way I'm calling the simple method or defining it is wrong.

I think you need to return something in your simple_method for Flask-Cache to cache the return value. I doubt it would just figure out which variable in your method to cache by itself.

Another thing is that you need a separate function to compute and cache your result like this:

def simple_method(self):
    @cache.cached(timeout=10, key_prefix='filters1')
    def compute_a():
        return a = 1
    return compute_a()

If you want to cache the method, use memoize

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM