gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 06:09:28 27 4
gpt4 key购买 nike

我正在使用 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"]]"

这是我必须手动完成的事情吗?

最佳答案

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

尝试在存储之前转换为 json 并在访问时转换回来。

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

在第 3 个答案(来自 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

在链接的问题中还有一些额外的要点值得一读。

关于Python将redis对象转换为原始数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50998856/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com