Storing a custom Python object in Redis -
i'm trying store custom, serializable python object in redis, have encountered strange behavior. set
method seems function, get
method returns value of object's __repr__
method. instance...
import redis # initialize redis connection pool rs = redis.redis(host='localhost', port=6379) # define custom class class somecustomobject(object): pass
when try set somecustomobject
value, appears work:
>>> rs.set('c', somecustomobject()) true
however, when get
value back, it's __repr__
string:
>>> rs.get('c') '<__main__.somecustomobject object @ 0x102496710>'
how store/get instance back? i've not had luck finding info on in the documentation, surely i'm not first 1 encounter this?
use pickle
using pickle module can serialize , deserialize python objects , pass them redis.
from answer - https://stackoverflow.com/a/20400288/4403600, this:
import pickle import redis # define custom class class somecustomobject(object): pass # initialize redis connection pool rs = redis.redis(host='localhost', port=6379) # pickle , set in redis rs.set('c', pickle.dumps(somecustomobject())) # redis , unpickle unpacked_object = pickle.loads(rs.get('c'))
further reading - https://docs.python.org/2/library/pickle.html
Comments
Post a Comment