python - 如何在模板错误时跳过 Flask 缓存

标签 python flask redis

我在 Redis 服务器上使用带有模板缓存的 Flask:

TIMEOUT = 60 * 60
cache = Cache(app.server, config={
    'CACHE_TYPE': 'redis',
    'CACHE_REDIS_HOST': "myredis",
    'CACHE_DEFAULT_TIMEOUT': TIMEOUT,
    'CACHE_REDIS_PORT': 6379,
})
# to disable caching
#app.config["CACHE_TYPE"] = "null"

然后使用@cache 装饰器

@cache.memoize(timeout=TIMEOUT)
def update_date():
    return manager.getData()

问题是当 manager.getData() 有错误或没有数据时,装饰器无论如何都会缓存响应。如何避免?

[更新]

我试过使用 unless 参数,根据文档应该是这样

unless – Default None. Cache will always execute the caching facilities unelss this callable is true. This will bypass the caching entirely.

像这样使用

@cache.memoize(timeout=TIMEOUT unless=DataLoader.instance.hasData)
    def update_date():
        return manager.getData()

其中 DataLoader 是一个 Singleton 实例,如果没有数据,hasData 方法将返回 None,如果没有数据,则返回 True它有数据,所以 getData 方法将计算数据并返回实例变量 self.data,它总是保存最后计算的数据或 None

class DataLoader(SingletonMixin):

    def __init__(self):
        self.data=None
    def hasData(self):
        if self.data is Not None:
            return True
        else:
            return None
    def getData(self):
        # calculate data
        res = self.computeData()
        if res is not None:
            self.data=res
        return self.data

但它似乎没有按预期工作。

最佳答案

The problem is that when manager.getData() has errors or no data the decorator will cache the response anyways. How to avoid it?

你检查过了吗?如果您查看 source code (我假设你正在使用 flask-caching 因为 flask-cache 没有维护超过 4 年)如果你从缓存中得到 None (rv 值)你不使用它,你调用你的 f 函数。如果 f 函数引发异常,则不会将任何内容保存到缓存中。

关于python - 如何在模板错误时跳过 Flask 缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55119872/

相关文章:

php - 使用redis实现消息队列报错,使用BLPOP报错

Python void 返回类型注解

python - 如何在 TPU 的其他模型中使用 keras 模型

python - "Connect" Actor 通过删除重叠或 "filling"的空话。碰撞检测

ruby-on-rails - 如何从 Resque worker 向 Redis 发送数据?

redis - 仅为特定的 redis 数据库而不是整个 redis 服务器设置持久性关闭(RDB)

python - Gtk-ERROR ** : GTK+ 2. x 检测到符号。不支持在同一进程中使用 GTK+ 2.x 和 GTK+ 3(Kivy 应用程序)

python - 我无法在 heroku 上部署我的 flask 应用程序

仅当我在 apache2 或 nginx 中部署 Flask 应用程序时,Python 中的 sqlite3 "OperationalError: unable to open database file"

python - py2neo中的节点可以继承吗?