how to store a complex object in redis (using redis-py)
Actually, you can store python objects in redis using the built-in module pickle.
Here is example.
import pickleimport redisr = redis.StrictRedis(host='localhost', port=6379, db=0)obj = ExampleObject()pickled_object = pickle.dumps(obj)r.set('some_key', pickled_object)unpacked_object = pickle.loads(r.get('some_key'))obj == unpacked_object
If your data is JSON-serializable, then that may be the better option than saving python pickles to an external database, since it's a more common standard outside of Python, is more human-readable on its own, and avoids a rather large attack vector.
JSON Example:
import jsonimport redisr = redis.StrictRedis(host='localhost', port=6379, db=0)images= [ {'type':'big', 'url':'....'}, {'type':'big', 'url':'....'}, {'type':'big', 'url':'....'},]# Convert python dict to JSON str and save to Redisjson_images = json.dumps(images)r.set('images', json_images)# Read saved JSON str from Redis and unpack into python dictunpacked_images = json.loads(r.get('images'))images == unpacked_images
python 3:
unpacked_images = json.loads(r.get('images').decode('utf-8'))images == unpacked_images
You can't create nested structures in Redis, meaning you can't (for example) store a native redis list inside a native redis hash-map.
If you really need nested structures, you might want to just store a JSON-blob (or something similar) instead. Another option is to store an "id"/key to a different redis object as the value of the map key, but that requires multiple calls to the server to get the full object.