Reputation: 7170
I'm trying to store a custom, serializable python object in Redis, but have encountered some strange behavior. The set
method seems to function, but the get
method only returns the value of the object's __repr__
method. For instance...
import redis
# initialize the redis connection pool
rs = redis.Redis(host='localhost', port=6379)
# define a custom class
class SomeCustomObject(object):
pass
When I try to set the SomeCustomObject
as a value, it appears to work:
>>> rs.set('c', SomeCustomObject())
True
However, when I get
the value back, it's just the __repr__
string:
>>> rs.get('c')
'<__main__.SomeCustomObject object at 0x102496710>'
How do I store/get the instance back? I've not had much luck finding any info on this in the documentation, but surely I'm not the first one to encounter this?
Upvotes: 10
Views: 7757
Reputation: 1960
Use Pickle
Using the pickle module you can serialize and deserialize Python objects and pass them to Redis.
From this so answer - https://stackoverflow.com/a/20400288/4403600, it would look like this:
import pickle
import redis
# define a custom class
class SomeCustomObject(object):
pass
# initialize the redis connection pool
rs = redis.Redis(host='localhost', port=6379)
# pickle and set in redis
rs.set('c', pickle.dumps(SomeCustomObject()))
# get from redis and unpickle
unpacked_object = pickle.loads(rs.get('c'))
Further reading - https://docs.python.org/2/library/pickle.html
Upvotes: 20