首页 > 解决方案 > 将压缩后的数据存储在 redis 中

问题描述

我有一个巨大的 python 字典,我想保存到 redis 缓存,然后让 API 处理程序直接从缓存中返回这个字典

我使用gzip先压缩字符串化的字典,然后再存储在缓存中

 transformed_object = {...big dictionary}

    byte_object = BytesIO()

    data = json.dumps(transformed_object)
    with gzip.GzipFile(fileobj=byte_object, mode="w") as f:
        f.write(data.encode())

    final_data = byte_object.getvalue()

我把它写到 Redis 缓存

context.redis.set(COMPLETE_GZIPPED_CACHE, final_data)

我有一个 API 处理程序,我想在其中返回 gzip 压缩的数据

    cache_list = redis.get(COMPLETE_GZIPPED_CACHE)
    self.finish(
        {
            "status": True,
            "cache_list": cache_list,
            "updated_at": datetime.datetime.now(),
        }
    )

问题是我收到以下错误

TypeError: Object of type 'bytes' is not JSON serializable

在返回前端之前,我是否需要先将字节解码回字符串?理想情况下,我希望前端处理解码

有一个更好的方法吗?

标签: pythonredistornado

解决方案


从其他帖子中弄清楚 - 编写了这样的函数并选择使用zlib

def convert_to_gzip_format(dict):
    stringified_object = json.dumps(dict).encode("utf-8")
    compressed_file = zlib.compress(stringified_object)

    base64_string = base64.b64encode(compressed_file).decode("ascii")
    return base64_string

这会将其作为 ascii 字符串保存到 redis。然后我pako.js在前端使用将上述内容解码为可读字符串。


推荐阅读