关于python:清除Django中的特定缓存

Clearing specific cache in Django

我正在为Django项目使用视图缓存。

它说缓存使用URL作为键,因此我想知道如果用户更新/删除对象,如何清除键之一的缓存。

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

我在用着:

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

如果post.id为1234,则似乎可行,但不是这样:

1
2
3
4
def edit_post(....):
    # stuff that saves the edits
    cache.delete('/post/%s/' % post.id)
    return Http.....


从django缓存文档中,它说cache.delete('key')应该足够了。 因此,我想到您可能会遇到两个问题:

  • 您的导入不正确,请记住必须从django.core.cache模块导入cache

    1
    2
    3
    4
    from django.core.cache import cache

    # ...
    cache.delete('my_url')
  • 您使用的密钥不正确(也许它使用了完整的URL,包括" domain.com")。 要检查确切的URL,可以进入shell:

    1
    2
    3
    4
    5
    6
    7
    8
    $ ./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 / ?

  • 我做了一个删除键的功能,以一些文本开头。 这有助于我删除动态键。

    列出已缓存的帖子

    1
    2
    3
    4
    5
    6
    def get_posts(tag, page=1):
        cached_data = cache.get('list_posts_home_tag%s_page%s' % (tag, page))
        if not cached_data:
            cached_data = mycontroller.get_posts(tag, page)
            cache.set('list_posts_home_tag%s_page%s' % (tag, page), cached_data, 60)
        return cached_data

    更新任何帖子时,请致电flush_cache

    1
    2
    3
    4
    def update(data):
        response = mycontroller.update(data)
        flush_cache('list_posts_home')
        return response

    flush_cache删除任何动态缓存

    1
    2
    3
    4
    def flush_cache(text):
        for key in list(cache._cache.keys()):
            if text in key:
                cache.delete(key.replace(':1:', ''))

    不要忘记从Django导入缓存

    1
    from django.core.cache import cache