Flask-Caching是一个用于Flask框架的缓存插件,既支持高度的自定义继承开发,也支持简单的缓存存取,简单的缓存存取如下

from flask import Flask
from flask_caching import Cache

app = Flask(__name__)
app_cache = Cache(config={'CACHE_TYPE': 'filesystem', "CACHE_DEFAULT_TIMEOUT": 10, 'CACHE_DIR': '/tmp'})
app_cache.init_app(app)

@app.route("/")
def index():
    code = random.randint(0,9)
    if code is not None:
        cache.set("code", code)
    return render_templete_striing("<html><body>your code is {{code}}</body></html>")

@app.route("/login/<code>")
def login(code):
    cache_code = cache.get("code")
    if code == cache_code
        return render_templete_striing("<html><body>valid {{code}} !</body></html>")
    return render_templete_striing("<html><body>invalid {{code}} !</body></html>")

然而当我需要持久化缓存的时候,却发现Flask-Caching - 文档里对缓存过期参数 CACHE_DEFAULT_TIMEOUT 的描述只有

The default timeout that is used if no timeout is specified. Unit of time is seconds.

经过一番查找,在How can I configure Flask-Cache with infinite timeout – stack overflow看到比较靠谱的答案

当使用 cache.set()的时候,如不传入timeout参数,则默认使用 CACHE_DEFAULT_TIMEOUT 参数的过期时间,如需持久化该缓存,则使用 timeout=0 即可

如下

from flask import Flask
from flask_caching import Cache

app = Flask(__name__)
app_cache = Cache(config={'CACHE_TYPE': 'filesystem', "CACHE_DEFAULT_TIMEOUT": 10, 'CACHE_DIR': '/tmp'})
app_cache.init_app(app)

cache.set("key", "value", timeout=0)