1

The Cache class provides a way for the cache to timeout when caching using cache.cache(timeout=TIMEOUT). But, it doesn't delete the cache automatically after the timeout interval. The only way to clear the cache is by calling cache.clear() which clears the entire cache, rather than only the cache of the function that you want to clear.

Is it possible to automatically clear all cache that have timed-out? And are there any other libraries that do so?

lahsuk
  • 1,134
  • 9
  • 20

1 Answers1

0

Flask-caching doesn't have any mechanism to delete cache/expired cache automatically.

But in Simple and FileSystemCache mode, it have a CACHE_THRESHOLD config setting, if the number of cache more than threshold setting, it will delete all expired cache and every cache that index divisible by three.

Flask-caching Simple mode source code (Version 1.10.1):

    def _prune(self):
        if len(self._cache) > self._threshold:
            now = time()
            toremove = []
            for idx, (key, (expires, _)) in enumerate(self._cache.items()):
                if (expires != 0 and expires <= now) or idx % 3 == 0:
                    toremove.append(key)
            for key in toremove:
                self._cache.pop(key, None)
            logger.debug("evicted %d key(s): %r", len(toremove), toremove)

Also, CACHE_THRESHOLD can be setting before initializing

from flask import Flask
from flask_caching import Cache

config = {
    "CACHE_TYPE": "SimpleCache",  
    "CACHE_THRESHOLD": 300 # It can be setting before initializing 
}
app = Flask(__name__)
app.config.from_mapping(config)
cache = Cache(app)

By and large, if you use these mode, you can write the schedule jobs to delete expired cache like above source code.

Vic
  • 758
  • 2
  • 15
  • 31