Skip to content

Commit 4975fd6

Browse files
author
Fabien Coelho
committed
implement RedisCache raw mode
1 parent 5c68a0c commit 4975fd6

File tree

3 files changed

+27
-17
lines changed

3 files changed

+27
-17
lines changed

CacheToolsUtils.py

+8-6
Original file line numberDiff line numberDiff line change
@@ -699,6 +699,7 @@ class RedisCache(MutableMapping):
699699
700700
:param cache: actual redis cache.
701701
:param ttl: time-to-live in seconds, used as default expiration (``ex``), default is 600.
702+
:param raw: whether to serialize keys and values, default is *False*.
702703
703704
Keys and values are serialized in *JSON*.
704705
@@ -710,24 +711,25 @@ class RedisCache(MutableMapping):
710711
cache = ctu.RedisCache(redis.Redis(host="localhost"), 3600)
711712
"""
712713

713-
def __init__(self, cache, ttl=600):
714+
def __init__(self, cache, ttl=600, raw=False):
714715
# import redis
715716
# assert isinstance(cache, redis.Redis)
716717
self._cache = cache
717718
self._ttl = ttl
719+
self._raw = raw
718720

719721
def clear(self): # pragma: no cover
720722
"""Flush Redis contents."""
721723
return self._cache.flushdb()
722724

723-
def _serialize(self, s) -> str:
724-
return json.dumps(s, sort_keys=True, separators=(",", ":"))
725+
def _serialize(self, s):
726+
return s if self._raw else json.dumps(s, sort_keys=True, separators=(",", ":"))
725727

726-
def _deserialize(self, s: str):
727-
return json.loads(s)
728+
def _deserialize(self, s):
729+
return s if self._raw else json.loads(s)
728730

729731
def _key(self, key):
730-
return json.dumps(key, sort_keys=True, separators=(",", ":"))
732+
return key if self._raw else json.dumps(key, sort_keys=True, separators=(",", ":"))
731733

732734
def __getitem__(self, index):
733735
val = self._cache.get(self._key(index))

docs/REFERENCE.md

+7-5
Original file line numberDiff line numberDiff line change
@@ -103,13 +103,13 @@ pay for them?
103103
When used with `cached`, the key is expected to be simple bytes for encryption.
104104
Consider `ToBytesCache` to trigger byte conversions.
105105
The output is also bytes, which may or may not suit the underlying cache, consider
106-
`BytesCache` if necessary.
106+
`BytesCache` if necessary, or using the `raw` option on `RedisCache`.
107107

108108
```python
109109
actual = redis.Redis(…)
110-
c0 = ctu.BytesCache(actual)
111-
c1 = ctu.EncryptedCache(c0, b"")
112-
cache = ctu.ToBytesCache(c1)
110+
red = ctu.RedisCache(actual, raw=True)
111+
enc = ctu.EncryptedCache(red, b"")
112+
cache = ctu.ToBytesCache(enc)
113113

114114
@cached(cache=PrefixedCache(cache, "foo."))
115115
def foo(what, ever):
@@ -155,7 +155,7 @@ pcache = ctu.PrefixedMemCached(mc_base, prefix="pic.")
155155

156156
## RedisCache
157157

158-
TTL'ed Redis wrapper, default ttl is 10 minutes.
158+
TTL'ed Redis wrapper, default ttl is 10 minutes and key/value JSON serialization.
159159
Also adds a `hits()` method to compute the cache hit ratio with data taken
160160
from the Redis server.
161161

@@ -168,6 +168,8 @@ cache = ctu.RedisCache(rd_base, ttl=60)
168168

169169
Redis stores arbitrary bytes. Key and values can be up to 512 MiB.
170170
Keeping keys under 1 KiB seems reasonable.
171+
Option `raw` allows to skip the serialization step, if you know that
172+
keys and values are scalars.
171173

172174
## PrefixedRedisCache
173175

test.py

+12-6
Original file line numberDiff line numberDiff line change
@@ -243,12 +243,11 @@ def test_redis():
243243
c0 = redis.Redis(host="localhost")
244244
c0.flushdb()
245245

246-
c1 = ctu.RedisCache(c0)
247-
c2 = ctu.BytesCache(c1)
248-
c3 = ctu.EncryptedCache(c2, SECRET, hsize=24)
249-
c4 = ctu.ToBytesCache(c3)
250-
c5 = ctu.DebugCache(c4, log)
251-
cache = ctu.LockedCache(c5, threading.RLock())
246+
c1 = ctu.RedisCache(c0, raw=True)
247+
c2 = ctu.EncryptedCache(c1, SECRET, hsize=24)
248+
c3 = ctu.ToBytesCache(c2)
249+
c4 = ctu.DebugCache(c3, log)
250+
cache = ctu.LockedCache(c4, threading.RLock())
252251
run_cached(cache)
253252
assert len(cache) >= 50
254253
assert cache[(1, 'a', True)] == 111
@@ -574,3 +573,10 @@ def test_encrypted_cache():
574573
assert "Hello" in scache
575574
assert scache["Hello"] == "World!"
576575
del scache["Hello"]
576+
# bytes again
577+
bcache = ctu.BytesCache(scache)
578+
bcache[b"Hello"] = b"World!"
579+
assert b"Hello" in bcache
580+
assert bcache[b"Hello"] == b"World!"
581+
del bcache[b"Hello"]
582+
assert b"Hello" not in bcache

0 commit comments

Comments
 (0)