2

I am using redis-py and whenever I store a list or a dict in the cache, running the get function return a string. how do I get back the original datatype?

cache = redis.StrictRedis(host='localhost', port=6379, decode_responses=True)
cache.set("posts",[["bob","My first post"],["mary","My second post"]])

cache.get("post")
>>>"[["bob","My first post"],["mary","My second post"]]"

Is this something that I have to do manually?

jinyus
  • 477
  • 7
  • 19

2 Answers2

5

The list of lists is your issue, as Redis doesn't like nested structures.

Try something like converting to json before storing and convert back on access.

Your issue is quite similar to how to store a complex object in redis (using redis-py)

In the 3rd answer (from CivFan) an example is given that would translate pretty directly for what it appears you are trying to do. For reference, the code snippet provided in that question/answer:

import json
import redis

r = redis.StrictRedis(host='localhost', port=6379, db=0)

images= [
    {'type':'big', 'url':'....'},
    {'type':'big', 'url':'....'},
    {'type':'big', 'url':'....'},
]

json_images = json.dumps(images)
r.set('images', json_images)
unpacked_images = json.loads(r.get('images'))
images == unpacked_images

There are some additional points to consider worth reading in the linked question as well.

tabbek
  • 866
  • 5
  • 9
  • serialize into JSON is an option. You might want to checkout the *rejson* module. It allows you to store JSON in Redis: https://github.com/RedisLabsModules/rejson and https://github.com/RedisLabs/rejson-py – hootnot Jun 23 '18 at 09:35
3

If you are storing standard json data, then you should use json module to serialize before putting into redis.

import json

val = json.dumps([["bob","My first post"],["mary","My second post"]])
redis_cache.set("posts",val)
str_val = redis_cache.get("posts")
obj = json.loads(str_val)

If you want to store any python object, use pickle to serialize

import pickle

val = pickle.dumps([["bob","My first post"],["mary","My second post"]])
redis_cache.set("posts",val)
str_val = redis_cache.get("posts")
obj = pickle.loads(str_val)
Heera Jaiswal
  • 681
  • 5
  • 3