Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing a custom Python object in Redis

Tags:

python

redis

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?

like image 714
TayTay Avatar asked Apr 07 '17 16:04

TayTay


People also ask

Can you store Python objects in Redis?

Actually, you can store python objects in redis using the built-in module pickle.

Is Python Redis client thread safe?

Redis itself is thread-safe no matter which connection pool do you use.


1 Answers

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

like image 86
Phillip Martin Avatar answered Oct 10 '22 21:10

Phillip Martin