2015-10-08 29 views
3

我想使用Flask-Cache來緩存不是視圖的函數的結果。但是,如果我裝飾視圖函數,它似乎只能工作。 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,它也可以。我認爲這是一個線索,緩存它自己正在被正確初始化,但我調用簡單方法或定義它的方式是錯誤的。

+0

編輯我的問題,謝謝。 – WebQube

+2

它看起來像你正在使用'simple_method'作爲更大的東西的一部分。你可以包括包裝類,以及你如何調用它? (就像現在一樣,你的例子不會運行,因爲'self'不會傳遞給'simple_method')。 –

+0

編輯我的問題 – WebQube

回答

0

我認爲你需要在Flask-Cache的simple_method中返回一些東西來緩存返回值。我懷疑它只是找出你的方法中的哪個變量來自己緩存。

另一件事是,你需要一個單獨的函數來計算和緩存你的結果是這樣的:

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

如果你希望緩存的方法,使用memoize

+0

感謝您的答案@ user1537085,返回一個值,但仍然沒有緩存 – WebQube