Get list of Cache Keys in Django

前端 未结 8 1955
暗喜
暗喜 2020-12-15 17:28

I\'m trying to understand how Django is setting keys for my views. I\'m wondering if there\'s a way to just get all the saved keys from Memcached. something like a cac

相关标签:
8条回答
  • 2020-12-15 17:37

    If this is not too out of date, I have had similar issue, due I have had to iterate over whole cache. I managed it, when I add something to my cache like in following pseudocode:

    #create caches key list if not exists
    if not my_cache.get("keys"):
        my_cache.set("keys", [])
    
    #add to my cache
    my_cache.set(key, value)
    
    #add key to keys
    if key not in my_cache.get("keys"):
        keys_list = my_cache.get("keys")
        keys_list.append(key)
        my_cache.set("keys", keys_list)
    
    0 讨论(0)
  • 2020-12-15 17:50

    You can use http://www.darkcoding.net/software/memcached-list-all-keys/ as explained in How do I check the content of a Django cache with Python memcached?

    0 讨论(0)
  • 2020-12-15 17:50

    You can use memcached_stats from: https://github.com/dlrust/python-memcached-stats. This package makes it possible to view the memcached keys from within the python environment.

    0 讨论(0)
  • 2020-12-15 17:52

    There are some weird workarounds you can do to get all keys from the command line, but there is no way to do this with memcached inside of Django. See this thread.

    0 讨论(0)
  • 2020-12-15 17:53

    Switch to using LocMemCache instead of MemcachedCache:

    CACHES = {
        'default': {
            'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
            'LOCATION': 'unique-snowflake',
        }
    }
    

    Then see the question Contents of locmem cache in Django?:

    from django.core.cache.backends import locmem
    print(locmem._caches)
    
    0 讨论(0)
  • 2020-12-15 17:55

    As mentioned there is no way to get a list of all cache keys within django. If you're using an external cache (e.g. memcached, or database caching) you can inspect the external cache directly.

    But if you want to know how to convert a django key to the one used in the backend system, django's make_key() function will do this.

    https://docs.djangoproject.com/en/1.8/topics/cache/#cache-key-transformation

    >>> from django.core.cache import caches
    >>> caches['default'].make_key('test-key')
    u':1:test-key'
    
    0 讨论(0)
提交回复
热议问题