Reputation: 4380
I've been using the redis-cli to get the hang of how redis works. I understand that using this tool I can do this:
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!"
What I cannot seem to figure out is how I would accomplish this with redis-py. It doesn't seem the set
commanded provided allows for an object-type or id. Thanks for your help.
Upvotes: 2
Views: 1047
Reputation: 4530
Another way: you can use RedisWorks
library.
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'}
And if you really need to use post.1
as key name in Redis:
>>> class Post(Root):
... pass
...
>>> post=Post()
>>> post.i1 = {'title':'Redis is cool!', 'author':'haye321'}
>>> print(post.i1)
{'author': 'haye321', 'title': 'Redis is cool!'}
>>>
If you check Redis
$ redis-cli
127.0.0.1:6379> type post.1
hash
Upvotes: 1
Reputation: 5981
You are setting individual fields of a Redis hash one by one (a hash is the common data structure in Redis to store objects).
A better way to do this is to use Redis HMSET command, that allows to set multiple fields of a given hash in one operation. Using Redis-py it will look like this:
import redis
redisdb = redis.Redis(host="localhost",db=1)
redisdb.hmset('post:1', {'title':'Redis is cool!', 'author':'haye321'})
update:
Of course you could have set Hash field members one by one using the HSET command, but it's less efficient as it requires one request per field:
import redis
redisdb = redis.Redis(host="localhost",db=1)
redisdb.hset('post:1', 'title', 'Redis is cool!')
redisdb.hset('post:1', 'author', 'haye321'})
Upvotes: 2