2012-01-09 686 views
4

我正在使用視圖緩存的Django項目。在Django中清除特定的緩存

它說緩存使用的URL作爲關鍵,所以我想知道如何清除一個密鑰的緩存,如果用戶更新/刪除對象。

舉例:用戶發佈博客文章爲domain.com/post/1234/ ..如果用戶編輯了該文件,我想通過在視圖末尾添加某種類型的delete cache命令來刪除該URL的緩存版本保存已編輯的帖子。

我使用:

@cache_page(60 * 60) 
def post_page(....): 

如果post.id是1234,它看起來這可能會奏效,但它不是:

def edit_post(....): 
    # stuff that saves the edits 
    cache.delete('/post/%s/' % post.id) 
    return Http..... 
+0

我的猜測是,你正在使用的密鑰是不正確的。您可以嘗試在您的memcached服務器上使用[此腳本](http://simple-and-basic.com/2008/10/list-memcached-keys.html)列出密鑰。一旦你有合適的密鑰,再次嘗試cache.delete(key)方法。 – stephenmuss 2012-01-09 06:07:54

+0

以下是更新後的django緩存文檔的鏈接: [Django Caches](https://docs.djangoproject.com/en/1.9/topics/cache/#django-s-cache-framework) – turtlefranklin 2016-06-24 13:38:43

回答

12

django cache docs,它說,cache.delete('key')應足夠。所以,我想到兩個問題,你可能有:

  1. 你的進口是不正確的,記住,你必須從django.core.cache模塊導入cache

    from django.core.cache import cache 
    
    # ... 
    cache.delete('my_url') 
    
  2. 關鍵你」重新使用是不正確的(也許它使用完整的網址,包括「domain.com」)。要檢查哪些是確切的網址,你可以進入你的shell:

    $ ./manage.py shell 
    >>> from django.core.cache import cache 
    >>> cache.has_key('/post/1234/') 
    # this will return True or False, whether the key was found or not 
    # if False, keep trying until you find the correct key ... 
    >>> cache.has_key('domain.com/post/1234/') # including domain.com ? 
    >>> cache.has_key('www.domain.com/post/1234/') # including www.domain.com ? 
    >>> cache.has_key('/post/1234') # without the trailing/? 
    
+2

這似乎是接受的答案。什麼是正確的關鍵?我有同樣的問題,我無法找到正確的密鑰。 – caliph 2016-07-11 18:44:47

+0

@caliph我也有這個問題。事實證明,Django的cache_page修飾器根據請求對象創建一個鍵,這是比文檔更好的解釋方式。因此,舉例來說,當所有事情都說完後,您將得到一個看起來像這樣的密鑰: 「:1:views.decorators.cache.cache_page..GET.3e144467194c80669ac0d860e0368097.ec0b8f79f7413e4479a39eb2bb0104f0.en-us.America/New_York」 。 有一個更簡潔的解釋[這裏](http://stackoverflow.com/a/2268583/5597611) – 2016-09-07 20:06:54