使用redis-py处理复杂对象

2 投票
2 回答
1035 浏览
提问于 2025-04-17 21:34

我一直在用redis-cli来了解redis是怎么工作的。我明白用这个工具我可以这样做:

127.0.0.1:6379> set post:1:title "Redis is cool!"
OK
127.0.0.1:6379> set post:1:author "haye321"
OK
127.0.0.1:6379> get post:1:title
"Redis is cool!"

但是我搞不明白怎么用redis-py来实现这个功能。看起来提供的set命令不支持对象类型或者ID。谢谢你的帮助。

2 个回答

1

还有一种方法:你可以使用 RedisWorks 这个库。

安装方法是用命令 pip install redisworks

>>> from redisworks import Root
>>> root = Root()
>>> root.item1 = {'title':'Redis is cool!', 'author':'haye321'}
>>> print(root.item1)  # reads it from Redis
{'title':'Redis is cool!', 'author':'haye321'}

如果你真的需要在 Redis 中使用 post.1 作为键名:

>>> class Post(Root):
...     pass
... 
>>> post=Post()
>>> post.i1 = {'title':'Redis is cool!', 'author':'haye321'}
>>> print(post.i1)
{'author': 'haye321', 'title': 'Redis is cool!'}
>>> 

如果你查看 Redis 的内容:

$ redis-cli
127.0.0.1:6379> type post.1
hash
2

你正在一个一个地设置Redis哈希中的各个字段(哈希是Redis中用来存储对象的常见数据结构)。

其实,有个更好的方法可以做到这一点,那就是使用Redis的HMSET命令,这个命令可以让你在一次操作中设置一个哈希的多个字段。用Redis-py来写的话,代码看起来是这样的:

import redis
redisdb = redis.Redis(host="localhost",db=1)
redisdb.hmset('post:1', {'title':'Redis is cool!', 'author':'haye321'})

更新:

当然,你也可以使用HSET命令一个一个地设置哈希字段,但这样效率就低了,因为每设置一个字段都需要发送一次请求:

import redis
redisdb = redis.Redis(host="localhost",db=1)
redisdb.hset('post:1', 'title', 'Redis is cool!')
redisdb.hset('post:1', 'author', 'haye321'})

撰写回答