Python 如何使用flask cache创建的缓存值
我正在应用程序中使用flask缓存,并尝试在单独的过程中预填充缓存。问题是我无法确定缓存值的存储格式 查看缓存的值,它们看起来像是被pickle了,但是缓存函数创建的值与普通的pickle值略有不同,不能直接取消pickle。下面是一个例子: 以下是我的观点:Python 如何使用flask cache创建的缓存值,python,flask,flask-cache,Python,Flask,Flask Cache,我正在应用程序中使用flask缓存,并尝试在单独的过程中预填充缓存。问题是我无法确定缓存值的存储格式 查看缓存的值,它们看起来像是被pickle了,但是缓存函数创建的值与普通的pickle值略有不同,不能直接取消pickle。下面是一个例子: 以下是我的观点: @app.route('/index') @cache.cached(timeout=60) def index(): return 'foo' 以下是我视图中存储在redis中的缓存值: >>> r = re
@app.route('/index')
@cache.cached(timeout=60)
def index():
return 'foo'
以下是我视图中存储在redis中的缓存值:
>>> r = redis.StrictRedis()
>>> r.keys()
[b'flask_cache_view//index']
>>> r.get('flask_cache_view//index')
b'!\x80\x03X\x03\x00\x00\x00fooq\x00.'
请注意,缓存的bytestring有一个前导“!”。与手动酸洗“foo”相比:
>>> import pickle
>>> pickle.dumps('foo')
b'\x80\x03X\x03\x00\x00\x00fooq\x00.'
后者可以取消勾选,但尝试取消勾选烧瓶缓存值会导致错误“\u pickle.UnpicklingError:无效的加载键,!”
因为我不完全理解这个问题,所以我不愿意实施解决方案(例如,在所有ByTestRing上删除/预先设置“!”)。我在这里走对了吗?根据
werkzeug.contrib.cache.RedisCache
用于区分整数和其他类型的值。这正是我要找的。非常感谢。
def dump_object(self, value):
"""Dumps an object into a string for redis. By default it serializes
integers as regular string and pickle dumps everything else.
"""
t = type(value)
if t in integer_types:
return str(value).encode('ascii')
return b'!' + pickle.dumps(value)
def load_object(self, value):
"""The reversal of :meth:`dump_object`. This might be called with
None.
"""
if value is None:
return None
if value.startswith(b'!'):
try:
return pickle.loads(value[1:])
except pickle.PickleError:
return None
try:
return int(value)
except ValueError:
# before 0.8 we did not have serialization. Still support that.
return value