1

我一直在使用 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。谢谢你的帮助。

4

2 回答 2

1

您正在一一设置 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命令一一设置 Hash 字段成员,但效率较低,因为它需要每个字段一个请求:

import redis
redisdb = redis.Redis(host="localhost",db=1)
redisdb.hset('post:1', 'title', 'Redis is cool!')
redisdb.hset('post:1', 'author', 'haye321'})
于 2014-03-09T22:59:09.837 回答
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'}

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

>>> 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
于 2016-08-30T06:08:18.173 回答