skip to Main Content
cache.set("determ_" + str(id), cache_object)

Am working with Django cache using Redis, these are sample of my cache keys

determ_1ba243f3-2eda-4feb-bf24-1aa4c0cd2171
appr_hist_2bfd55e4-22c1-4cc3-a913-8ac2cde3801b
appr_act_5a18c351-e172-4369-9a4b-118c3df5b25a

but i get challenge when i want to delete cache using some part of key like determ_, appr_hist_, appr_act_

How will manage to accomplish this ?

from django.core.cache import cache

class CacheManager:
    
    @classmethod
    def delete_cache(self, prefixes = []):
        for pattern in prefixes:
            cache.delete(pattern)

        return True
CacheManager.delete_cache(['determ_','appr_hist_', 'det_appr','appr_act_','deter_sect_'])

2

Answers


  1. Chosen as BEST ANSWER

    Thank you so much @Guy Royse for the great inputs. I use the idea and build this method and now it work fine thought i will need to deal with my policies and performance

    import redis
    
    class CacheManager:
    
        
        @classmethod
        def delete_cache(self, prefixes = []):
            redis_client = redis.from_url('redis://127.0.0.1:6379/1')
            keys = redis_client.scan_iter("fcrs_:1:*")
            for key in keys:
                for prefix in prefixes:
                    clear_key = str(key.decode('utf-8')).split(":")
                    if prefix in clear_key[2]:
                        print(f": Found keys for prefix '{prefix}':", str(key.decode('utf-8')))
                        redis_client.delete(key)
            
            return True
    

  2. I can’t speak for Django, but Redis doesn’t have a patterned delete feature. The way this is typically done works but it not performant.

    It involves the use of the SCAN command to get all the keys that match a pattern. SCAN is an O(N) operation where N is the number of keys you have in Redis. Then, you issue an UNLINK on all of the fields. The UNLINK is variadic so you can pass in all the matching keys to it.

    The KEYS and DEL commands will work as well but are even less performant. KEYS blocks Redis while it runs and other clients then can’t use Redis. DEL blocks Redis until the memory is freed while UNLINK returns and then frees the memory.

    Not sure if you can get to any of these commands from Django, but I hope this helps.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search