python - 将压缩后的数据存储在 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
在返回前端之前,我是否需要先将字节解码回字符串?理想情况下,我希望前端处理解码
有一个更好的方法吗?
解决方案
从其他帖子中弄清楚 - 编写了这样的函数并选择使用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
在前端使用将上述内容解码为可读字符串。
推荐阅读
- android - 如何避免flutter中的内存不足?
- javascript - 如果我想为数组的单个索引提供多个元素,如何在 javascript 中填充数组
- python - 使用 ahk 库将击键发送到记事本
- mysql - 当一个数据有撇号标记时,ajax 请求出错(无效的 json 响应)
- python - 在 Networkx 中映射两个图
- r - 如果月-年组合不等于系统的月-年,则从同一月的去年值交换值的结果
- components - 如何在 Svelte 中的多个插槽和它们的父级之间共享状态
- apache-pig - 阿帕奇猪查询
- sql - EXECUTE ('CALL SCHEMA.PROC')、CALL SCHEMA.PROC 和 EXCEUTE 之间是否存在性能差异
- python - 计算派生列