在将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 theerror
exception if any error occurs.
关于django - 在保存到缓存之前先压缩Python对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3509878/