虽然利用set_response_callback
对于简单的数据类型来说很好,但如果你想知道存储字典、列表、元组等内容的最快和最简单的方法——并保留它们可能包含或可能不包含的 Python 原生数据类型——我推荐使用python的内置pickle
库:
# Imports and simplified client setup
>>> import pickle
>>> import redis
>>> client = redis.Redis()
# Store a dictionary
>>> to_store = {'a': 1, 'b': 'A string!', 'c': [1, True, False, 14.4]}
>>> client.set('TestKey', pickle.dumps(to_store))
True
# Retrieve the dictionary you just stored.
>>> retrieved = pickle.loads(client.get('TestKey'))
{'a': 1, 'b': 'A string!', 'c': [1, True, False, 14.4]}
这是一个简单的客户端,它将减少pickle
上述示例中的样板文件,并为您提供一个干净的接口,用于在 Redis 中存储和检索本机 python 数据类型:
"""Redis cache."""
import pickle
import redis
redis_host = redis.Redis()
class PythonNativeRedisClient(object):
"""A simple redis client for storing and retrieving native python datatypes."""
def __init__(self, redis_host=redis_host):
"""Initialize client."""
self.client = redis_host
def set(self, key, value, **kwargs):
"""Store a value in Redis."""
return self.client.set(key, pickle.dumps(value), **kwargs)
def get(self, key):
"""Retrieve a value from Redis."""
val = self.client.get(key)
if val:
return pickle.loads(val)
return None
redis_client = PythonNativeRedisClient()
用法:
>>> from some_module import redis_client
>>> to_store = {'a': 1, 'b': 'A string!', 'c': [1, True, False, 14.4]}
>>> redis_client.set('TestKey', to_store)
True
>>> retrieve = redis_client.get('TestKey')
{'a': 1, 'b': 'A string!', 'c': [1, True, False, 14.4]}