如何从python将字典存储在redis中



我正试图通过redis在内存中存储一个python dict,我正在遵循pypi文档,当我尝试实例化RedisCluster时,我得到了这个错误:

from redis.cluster import RedisCluster as Redis # this line works
rc = Redis(host='localhost', port=6379) # here is the problem
Traceback (most recent call last):
File "/home/developer/.pyenv/versions/redisTesting/lib/python3.9/site-packages/redis/cluster.py", line 1306, in initialize
raise RedisClusterException(
redis.exceptions.RedisClusterException: Cluster mode is not enabled on this node
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/home/developer/.pyenv/versions/3.9.5/lib/python3.9/code.py", line 90, in runcode
exec(code, self.locals)
File "<input>", line 1, in <module>
File "/home/developer/.pyenv/versions/redisTesting/lib/python3.9/site-packages/redis/cluster.py", line 507, in __init__
self.nodes_manager = NodesManager(
File "/home/developer/.pyenv/versions/redisTesting/lib/python3.9/site-packages/redis/cluster.py", line 1128, in __init__
self.initialize()
File "/home/developer/.pyenv/versions/redisTesting/lib/python3.9/site-packages/redis/cluster.py", line 1334, in initialize
raise RedisClusterException(
redis.exceptions.RedisClusterException: ERROR sending "cluster slots" command to redis server 127.0.0.1:6379. error: Cluster mode is not enabled on this node

我知道问题是Cluster mode is not enabled on this node,但我没有找到解决这个错误的方法,如何在节点上启用集群模式?

此外,我找到了一种方法,用将这个dict存储在内存中

import redis
r = redis.Redis()
r.hmset({
"color": "green",
"price": 99.99,
"style": "baseball",
"quantity": 200,
"npurchased": 0,
})

但这给了我一个不推荐的警告<input>:1: DeprecationWarning: Redis.hmset() is deprecated. Use Redis.hset() instead.,当我试图使用r.hset((时,终端给了我redis.exceptions.DataError: Invalid input of type: 'dict'. Convert to a bytes, string, int or float first.

将redis.cluster更改为redis,连接将成功。

#from redis.cluster import RedisCluster as Redis # this line works (but assumes you are connecting to Redis Cluster)
from redis import Redis
rc = Redis(host='localhost', port=6379) 

如前所述,hmset已弃用。相反,您应该使用hset,它可以使用mapping参数接收字典作为输入(只要它没有嵌套(。

另一个观察结果是,在调用hset时缺少映射键名称。所以这应该有效:

r.hmset("you_key_name", {
"color": "green",
"price": 99.99,
"style": "baseball",
"quantity": 200,
"npurchased": 0,
})

如果您需要嵌套功能,那么添加json转储,如下所示:

r.hmset("you_key_name", {
"color": "green",
"price_json": json.dumps({"val":99.99, "currency": "$"})
"style": "baseball",
"quantity": 200,
"npurchased": 0,
})

最新更新