Invalidating a path from the Django cache recursively

后端 未结 3 424
抹茶落季
抹茶落季 2020-12-24 04:25

I am deleting a single path from the Django cache like this:

from models                   import Graph
from django.http              import HttpRequest
from         


        
3条回答
  •  长情又很酷
    2020-12-24 04:53

    Another option is to use a cache that supports tagging keys and evicting keys by tag. Django's built-in cache API does not have support for this approach. But at least one cache backend (not part of Django proper) does have support.

    DiskCache* is an Apache2 licensed disk and file backed cache library, written in pure-Python, and compatible with Django. To use DiskCache in your project simply install it and configure your CACHES setting.

    Installation is easy with pip:

    $ pip install diskcache
    

    Then configure your CACHES setting:

    CACHES = {
        'default': {
            'BACKEND': 'diskcache.DjangoCache',
            'LOCATION': '/tmp/path/to/directory/',
        }
    }
    

    The cache set method is extended by an optional tag keyword argument like so:

    from django.core.cache import cache
    
    cache.set('/graph/123', value, tag='/graph/123')
    cache.set('/graph/123/2009-08-01/2009-10-21', other_value, tag='/graph/123')
    

    diskcache.DjangoCache uses a diskcache.FanoutCache internally. The corresponding FanoutCache is accessible through the _cache attribute and exposes an evict method. To evict all keys tagged with /graph/123 simply:

    cache._cache.evict('/graph/123')
    

    Though it may feel awkward to access an underscore-prefixed attribute, the DiskCache project is stable and unlikely to make significant changes to the DjangoCache implementation.

    The Django cache benchmarks page has a discussion of alternative cache backends.

    • Disclaimer: I am the original author of the DiskCache project.

提交回复
热议问题