Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to store a complex object in redis (using redis-py)

The hmset function can set the value of each field, but I found that if the value itself is a complex structured object, the value return from hget is a serialized string, not the original object

e.g

images= [{'type':'big', 'url':'....'},      {'type':'big', 'url':'....'},      {'type':'big', 'url':'....'}]     redis = Redis() redis.hset('photo:1', 'images', images)  i = redis.hget('photo:1', 'images') print type(i) 

the type of i is a string, not a python object, is there any way to solve this problem besides manually parse each fields?

like image 368
yuan Avatar asked Mar 05 '13 09:03

yuan


People also ask

How do I store a Python object in Redis?

Redis stores everything as a string, hence we can save the python object as a binary string. One of the easiest ways to dump and load binary in Python for Python Objects is using the python module pickle.

How do I save a dictionary in Redis?

you can pickle your dict and save as string. pickle can be dangerous if mishandled. Use msgpack for better serialization of data before storing it into Redis. Pickling has also the important down-part that you cannot debug the stored data in Redis as they are binary.

What is Redis StrictRedis?

source code object --+ | StrictRedis. Implementation of the Redis protocol. This abstract class provides a Python interface to all Redis commands and an implementation of the Redis protocol. Connection and Pipeline derive from this, implementing how the commands are sent and received to the Redis server.


2 Answers

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

Here is example.

import pickle import redis  r = 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 
like image 148
Kyrylo Perevozchikov Avatar answered Sep 19 '22 19:09

Kyrylo Perevozchikov


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 json import redis  r = 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 Redis json_images = json.dumps(images) r.set('images', json_images)  # Read saved JSON str from Redis and unpack into python dict unpacked_images = json.loads(r.get('images')) images == unpacked_images 

python 3:

unpacked_images = json.loads(r.get('images').decode('utf-8')) images == unpacked_images 
like image 28
CivFan Avatar answered Sep 17 '22 19:09

CivFan