[Django]-Enumerating keys in Django Database Cache

3👍

Assuming you are using MySQL as your DB backend this sub class of the DatabaseCache should work to return a dictionary of all the results from a LIKE type query on cache keys.

class DatabaseCacheExtended(DatabaseCache):
    def get_where(self, query, default=None, version=None):
        db = router.db_for_read(self.cache_model_class)
        table = connections[db].ops.quote_name(self._table)

        with connections[db].cursor() as cursor:
            cursor.execute("SELECT cache_key, value, expires FROM %s "
                           "WHERE cache_key LIKE %%s" % table, [query])
            rows = cursor.fetchall()
        if len(rows) < 1:
            return {}
        return_d ={}
        for row in rows:
            value = connections[db].ops.process_clob(row[1])
            return_d[row[0]] = pickle.loads(base64.b64decode(force_bytes(value)))
        return return_d

Then you just need to change the registered backend in your settings.py

    'bla_stats': {
        'BACKEND': 'path.to.DatabaseCacheExtended',
        'LOCATION': 'django_bla_stats_cache',
     }

Example:

>>> from django.core.cache import caches
>>> cache = caches['bla_stats']
>>> cache.get_where("b_%")
... {"b_key1":"val1", "b_key2":"val2"}

1👍

Django’s cache API doesn’t offer what you are looking for, so none of the implementations will either. One solution would be to create your own backend.

You’re still going to have to muck around some SQL queries, but you can subclass DatabaseCache to create your own custom backend. Add a method that allows you to query for keys by prefix, or to delete by prefix, and then wrap that into a management command for easy access.

👤JSTL

Leave a comment