Python将Redis对象转换为原始数据类型

时间:2018-06-23 07:10:59

标签: python redis

我正在使用redis-py,并且每当我在高速缓存中存储列表或字典时,运行get函数都会返回一个字符串。如何获取原始数据类型?

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"]]"

这是我必须手动执行的吗?

2 个答案:

答案 0 :(得分:3)

列表列表是您的问题,因为Redis不喜欢嵌套结构。

在存储之前尝试进行转换为json之类的操作,然后在访问时进行转换。

您的问题与how to store a complex object in redis (using redis-py)

非常相似

在第三个答案(来自CivFan)中,给出了一个示例,该示例将直接转换为您尝试执行的操作。作为参考,该问题/答案中提供的代码段:

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

在链接的问题中还需要考虑一些其他要点。

答案 1 :(得分:0)

如果要存储标准json数据,则应在放入redis之前使用json模块进行序列化。

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)

如果要存储任何python对象,请使用pickle进行序列化

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)