我在 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/