清除Django中的特定缓存

Bre*_*den 8 python django memcached django-cache

我正在为django项目使用视图缓存.

它说缓存使用URL作为密钥,所以我想知道如果用户更新/删除对象,如何清除其中一个密钥的缓存.

例如:用户将博客帖子发布到domain.com/post/1234/..如果用户编辑了该文章,我想通过在保存编辑后的帖子的视图末尾添加某种删除缓存命令来删除该URL的缓存版本.

我正在使用:

@cache_page(60 * 60)
def post_page(....):
Run Code Online (Sandbox Code Playgroud)

如果post.id是1234,似乎这可能会起作用,但它不是:

def edit_post(....):
    # stuff that saves the edits
    cache.delete('/post/%s/' % post.id)
    return Http.....
Run Code Online (Sandbox Code Playgroud)

jul*_*ria 18

django缓存文档中,它说cache.delete('key')应该足够了.所以,我想到了你可能遇到的两个问题:

  1. 您的导入不正确,请记住您必须cachedjango.core.cache模块导入:

    from django.core.cache import cache
    
    # ...
    cache.delete('my_url')
    
    Run Code Online (Sandbox Code Playgroud)
  2. 您使用的密钥不正确(可能使用完整的URL,包括"domain.com").要检查哪个是确切的URL,您可以进入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 / ?
    
    Run Code Online (Sandbox Code Playgroud)

  • 这似乎是公认的答案.什么是正确的钥匙?我确实有同样的问题,我找不到正确的密钥. (2认同)
  • @caliph我也有这个问题.事实证明,django的cache_page装饰器根据请求对象创建了一个密钥,这是一种比文档更好的解释方法.":1:views.decorators.cache.cache_page..GET.3e144467194c80669ac0d860e0368097.ec0b8f79f7413e4479a39eb2bb0104f0.en-us.America /纽约"因此,例如,你会当一切都说过和做过,看起来像这样的关键告终.有一个更简洁的解释[这里](http://stackoverflow.com/a/2268583/5597611) (2认同)