4

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.

WebQube
  • 8,510
  • 12
  • 51
  • 93
  • Did you ever get this to work? I think this solves your problem (but not mine) - https://stackoverflow.com/questions/55474340/python-flask-opencv-how-do-i-cache-an-arbitrary-opencv-object-between-request – jtlz2 Apr 02 '19 at 15:10

1 Answers1

0

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

user1537085
  • 404
  • 5
  • 18