2013-03-20 37 views
1

在我的意見,我有以下Django的緩存得到過期項

@require_POST 
def loadVals(request): 
    result = //do some heavy calculations 
    return HttpResponse(json.dumps({"data": result}), content_type="application/json") 

現在我已經添加了一個緩存,這樣,我沒有執行「重calclations」所有的時間。因此,新的代碼看起來像

settings.py

CACHES = { 
'default': { 
    'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 
    'LOCATION': 'unique-snowflake' 
} 

}

views.py

from django.core.cache import get_cache 

@require_POST 
def loadVals(request): 
    cache = get_cache('default') 
    result = cache.get('res') 
    if result == NONE: 
    result = //do some heavy calculations 
    cache.set('res', result, 30) 
    return HttpResponse(json.dumps({"data": result}), content_type="application/json") 
    else: 
    return HttpResponse(json.dumps({"data": result}), content_type="application/json") 

我想要做的卻是,即使是高速緩存已經過期,我想保存前端用戶一些等待時間(因爲繁重的計算),並且只返回最後過期的值。 然後刷新緩存。

我如何

1)獲取過期緩存的值?因爲如果緩存已過期,cache.get('res')將返回NONE

2)在返回HttpResponse語句之後進行調用以刷新緩存值並執行大量計算(其中返回statmenet剛剛返回了過期值)或者可能通過異步調用來做到這一點?

回答

2

首先,你的代碼有一些語法問題。 其次,您無法從django緩存中獲取過期的值。過期的值一旦到期就會被刪除,之後它們就不存在了。

如果您希望爲這種情況存儲更長的值,則需要將它們存儲在更持久的存儲器(如數據庫)中,而不是爲此創建緩存。

或者你可以緩存你的結果兩次其中一個是長,並從第二高速緩存服務:

from django.core.cache import get_cache 

@require_POST 
def loadVals(request): 
    cache = get_cache('default') 
    result = cache.get('res') or cache.get('res_long') 
    if result is None: 
     result = //do some heavy calculations 
     cache.set('res', result, 30) 
     cache.set('res_long', result, 60*60*24*7) # cache for a week 
    return HttpResponse(json.dumps({"data": result}), content_type="application/json") 

這仍然不是一個偉大的方法,因爲你還必須做一些事情來重新緩存短緩存。此外,它不是很好,因爲你用雙重數據超載你的緩存後端。

如果您希望用戶始終獲取緩存內容,請嘗試使用Celery作爲後臺任務來緩存它。

0

這裏是我工作:

1)創建一個全局變量,當你設置緩存,也設置這個全局變量。如果緩存已過期,則您的全局變量仍處於過期值範圍內,因此請發送該響應。並使用線程更新緩存和全局變量。

2)使用Python穿線

import threading 
def loadVals(): 
    threading.Thread(group=None, target=methodToDoheavyCalculations).start() 
    # return the expired cache in the meanwhile 
    return HttpResponse(json.dumps(EXPIRED_VALUES), content_type="application/json") 
+0

尼斯使用螺紋。不幸的是,wsgi沒有保證這個過程將在下一個請求中出現。所以使用線程永久緩存是一種反模式。 – Wtower 2016-12-23 08:36:20