【问题标题】:How to automatically clear cache of Flask-Caching after TIMEOUT interval?如何在 TIMEOUT 间隔后自动清除 Flask-Caching 的缓存?
【发布时间】:2020-10-29 17:48:50
【问题描述】:

Cache 类提供了一种在使用 cache.cache(timeout=TIMEOUT) 进行缓存时缓存超时的方法。但是,它不会在超时间隔后自动删除缓存。清除缓存的唯一方法是调用cache.clear(),它会清除整个缓存,而不仅仅是要清除的函数的缓存。

是否可以自动清除所有已超时的缓存?还有其他图书馆可以这样做吗?

【问题讨论】:

    标签: python caching flask-caching


    【解决方案1】:

    Flask-caching 没有任何机制来自动删除缓存/过期缓存。

    但在SimpleFileSystemCache模式下,它有一个CACHE_THRESHOLD的配置设置,如果缓存的数量超过threshold设置,它会删除所有过期的缓存和每个索引可分割的缓存三个

    Flask-cachingSimple模式源码(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)
    

    另外,CACHE_THRESHOLD 可以在初始化之前设置

    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)
    

    总的来说,如果你使用这些模式,你可以像上面的源代码一样编写调度作业来删除过期的缓存。

    【讨论】:

      猜你喜欢
      • 2016-07-10
      • 2022-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-19
      • 2014-08-19
      • 2020-01-20
      • 1970-01-01
      相关资源
      最近更新 更多