| 1 |
import asyncio |
| 2 |
import zlib |
| 3 |
|
| 4 |
from aiocache import Cache |
| 5 |
from aiocache.serializers import BaseSerializer |
| 6 |
|
| 7 |
|
| 8 |
class CompressionSerializer(BaseSerializer): |
| 9 |
|
| 10 |
# This is needed because zlib works with bytes. |
| 11 |
# this way the underlying backend knows how to |
| 12 |
# store/retrieve values |
| 13 |
DEFAULT_ENCODING = None |
| 14 |
|
| 15 |
def dumps(self, value): |
| 16 |
print("I've received:\n{}".format(value)) |
| 17 |
compressed = zlib.compress(value.encode()) |
| 18 |
print("But I'm storing:\n{}".format(compressed)) |
| 19 |
return compressed |
| 20 |
|
| 21 |
def loads(self, value): |
| 22 |
print("I've retrieved:\n{}".format(value)) |
| 23 |
decompressed = zlib.decompress(value).decode() |
| 24 |
print("But I'm returning:\n{}".format(decompressed)) |
| 25 |
return decompressed |
| 26 |
|
| 27 |
|
| 28 |
cache = Cache(Cache.REDIS, serializer=CompressionSerializer(), namespace="main") |
| 29 |
|
| 30 |
|
| 31 |
async def serializer(): |
| 32 |
text = ( |
| 33 |
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt" |
| 34 |
"ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation" |
| 35 |
"ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in" |
| 36 |
"reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur" |
| 37 |
"sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit" |
| 38 |
"anim id est laborum.") |
| 39 |
await cache.set("key", text) |
| 40 |
print("-----------------------------------") |
| 41 |
real_value = await cache.get("key") |
| 42 |
compressed_value = await cache.raw("get", "main:key") |
| 43 |
assert len(compressed_value) < len(real_value.encode()) |
| 44 |
|
| 45 |
|
| 46 |
async def test_serializer(): |
| 47 |
await serializer() |
| 48 |
await cache.delete("key") |
| 49 |
await cache.close() |
| 50 |
|
| 51 |
|
| 52 |
if __name__ == "__main__": |
| 53 |
asyncio.run(test_serializer()) |