menu Chancel's blog
rss_feed
Chancel's blog
有善始者实繁,能克终者盖寡。

FlaskCaching过期

作者:Chancel Yang, 创建:2021-06-16, 字数:1564, 已阅:99, 最后更新:2021-06-16

这篇文章更新于 1044 天前,文中部分信息可能失效,请自行甄别无效内容。

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

Python
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 即可

如下

Python
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)

[[replyMessage== null?"发表评论":"发表评论 @ " + replyMessage.m_author]]

account_circle
email
web_asset
textsms

评论列表([[messageResponse.total]])

还没有可以显示的留言...
[[messageItem.m_author]] [[messageItem.m_author]]
[[messageItem.create_time]]
[[getEnviron(messageItem.m_environ)]]
[[subMessage.m_author]] [[subMessage.m_author]] @ [[subMessage.parent_message.m_author]] [[subMessage.parent_message.m_author]]
[[subMessage.create_time]]
[[getEnviron(messageItem.m_environ)]]