如何使用flask-cache创建的缓存值

时间:2015-08-19 11:29:56

标签: python flask flask-cache

我在应用程序中使用flask-cache并尝试在单独的进程中预填充缓存。问题是我无法弄清楚缓存值的格式。

查看缓存的值,看起来它们已被腌制,但缓存函数创建的值与正常的腌制值略有不同,并且无法直接打开。这是一个例子:

这是我的瓶子视图:

@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.'

后者可以是unpickled,但是试图取消使用flask-cache值会导致错误" _pickle.UnpicklingError:无效的加载密钥,'!'。"

因为我没有完全理解这个问题,所以我不习惯实施解决方案(例如删除/预先添加'!'所有字节串)。我在这里走在正确的轨道上吗?

1 个答案:

答案 0 :(得分:2)

根据werkzeug.contrib.cache.RedisCache code

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

!用于区分整数和其他类型的值。