Clearing specific cache in Django

前端 未结 3 1053
没有蜡笔的小新
没有蜡笔的小新 2020-12-30 05:33

I am using view caching for a django project.

It says the cache uses the URL as the key, so I\'m wondering how to clear the cache of one of the keys if a user update

3条回答
  •  半阙折子戏
    2020-12-30 06:03

    I make a function to delete key starting with some text. This help me to delete dynamic keys.

    list posts cached

    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
    

    when update any post, call flush_cache

    def update(data):
        response = mycontroller.update(data)
        flush_cache('list_posts_home')
        return response
    

    flush_cache to delete any dynamic cache

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

    Do not forget to import cache from django

    from django.core.cache import cache
    

提交回复
热议问题