Skip to main content
 首页 » 编程设计

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

2024年10月24日15lautakyan007

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

查看缓存值,它们看起来像是被腌制过的,但缓存函数创建的值与普通腌制值略有不同,不能直接取消腌制。这是一个例子:

这是我的 flask View :

@app.route('/index') 
@cache.cached(timeout=60) 
def index(): 
    return 'foo' 

这是我 View 中的缓存值,存储在 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.' 

注意缓存的字节串有一个前导'!'。与手动酸洗“foo”相比:

>>> import pickle 
>>> pickle.dumps('foo') 
b'\x80\x03X\x03\x00\x00\x00fooq\x00.' 

后者可以解封,但尝试解封 flask-cache 值会导致错误“_pickle.UnpicklingError:加载 key 无效,'!'。”

因为我不完全理解这个问题,所以我不太愿意实现解决方案(例如,删除/在所有字节串上添加“!”)。我走在正确的轨道上吗?

请您参考如下方法:

原始答案(pre flask 1.0)

根据 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 

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

更新:Flask 1+ (cachelib.redis.RedisCache)

RedisCache 后端是 here现在但是序列化被移到了一个单独的类中 RedisSerializer .

存储有点不同。评论保持不变,但它现在只是腌制一切。

def dumps(self, value: _t.Any, protocol: int = pickle.HIGHEST_PROTOCOL) -> bytes: 
    """Dumps an object into a string for redis. By default it serializes 
    integers as regular string and pickle dumps everything else. 
    """ 
    return b"!" + pickle.dumps(value, protocol)