django - 在保存到缓存之前先压缩Python对象

标签 django caching memcached compression

在将Python对象(列表,字典,字符串等)保存到高速缓存中并从高速缓存中读取后解压缩的快速方法是什么?

我正在使用Django,我希望直接在Django的缓存后端中添加压缩/解压缩支持,从而使其对我所有的Django应用程序都可用。

我看着django/core/cache/backends/memcached.py

import cmemcache as memcache

class CacheClass(BaseCache):

    def __init__(self, server, params):
        BaseCache.__init__(self, params)
        self._cache = memcache.Client(server.split(';'))

    def get(self, key, default=None):
        val = self._cache.get(smart_str(key))
        if val is None:
            return default
        return val

    def set(self, key, value, timeout=0):
        self._cache.set(smart_str(key), value, self._get_memcache_timeout(timeout))

看来泡菜/腌菜是由cmemcache库完成的。我不知道将压缩/解压缩代码放在哪里。

最佳答案

首先-您确定需要吗?您的数据结构是否太大而无法在缓存中进行未压缩的存储?压缩/解压缩会产生开销,这可能会使您一开始通过缓存获得的任何 yield 无效。

如果确实需要压缩,则可能要使用zlib

如果要使用zlib,则可能需要尝试compress方法中可用的不同压缩级别,以平衡CPU时间与压缩级别:

zlib.compress(string[, level])
Compresses the data in string, returning a string contained compressed data. level is an integer from 1 to 9 controlling the level of compression; 1 is fastest and produces the least compression, 9 is slowest and produces the most. The default value is 6. Raises the error exception if any error occurs.

关于django - 在保存到缓存之前先压缩Python对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3509878/

相关文章:

django - 单元测试权限

caching - 清除 Apigee 中的整个缓存

spring - 是否可以使用 Spring 的缓存抽象和 redis 创建多个缓存存储?

django - Django Cache cache.set不存储数据

python - 缓存一个大对象并从缓存中快速读取 flask

django - 在 django-apps 中查找静态文件和模板的顺序

python - 在 Django views.py 中使用 cv2.imread() 读取图像时出错

python - Django Rest 框架 HyperLinkedRelatedField : allow id instead of url for POSTS requests

php - clearstatcache + include_path + session

java - Memcache key 生成策略