我正在使用 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"]]"
Run Code Online (Sandbox Code Playgroud)
这是我必须手动做的事情吗?
小智 5
列表列表是您的问题,因为 Redis 不喜欢嵌套结构。
在存储之前尝试转换为 json 并在访问时转换回来。
您的问题与如何在 redis 中存储复杂对象非常相似(使用 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
Run Code Online (Sandbox Code Playgroud)
在链接的问题中还有一些值得考虑的额外要点。