Serializers

Serializers can be attached to backends in order to serialize/deserialize data sent and retrieved from the backend. This allows to apply transformations to data in case you want it to be saved in a specific format in your cache backend. For example, imagine you have your Model and want to serialize it to something that Redis can understand (Redis can’t store python objects). This is the task of a serializer.

To use a specific serializer:

>>> from aiocache import Cache
>>> from aiocache.serializers import PickleSerializer
cache = Cache(Cache.MEMORY, serializer=PickleSerializer())

Currently the following are built in:

NullSerializer

class aiocache.serializers.NullSerializer(*args, encoding=<object object>, **kwargs)[source]

This serializer does nothing. Its only recommended to be used by aiocache.SimpleMemoryCache because for other backends it will produce incompatible data unless you work only with str types because it store data as is.

DISCLAIMER: Be careful with mutable types and memory storage. The following behavior is considered normal (same as functools.lru_cache):

cache = Cache()
my_list = [1]
await cache.set("key", my_list)
my_list.append(2)
await cache.get("key")  # Will return [1, 2]
dumps(value)[source]

Returns the same value

loads(value)[source]

Returns the same value

StringSerializer

class aiocache.serializers.StringSerializer(*args, encoding=<object object>, **kwargs)[source]

Converts all input values to str. All return values are also str. Be careful because this means that if you store an int(1), you will get back ‘1’.

The transformation is done by just casting to str in the dumps method.

If you want to keep python types, use PickleSerializer. JsonSerializer may also be useful to keep type of symple python types.

dumps(value)[source]

Serialize the received value casting it to str.

Parameters:

value – obj Anything support cast to str

Returns:

str

loads(value)[source]

Returns value back without transformations

PickleSerializer

class aiocache.serializers.PickleSerializer(*args, protocol=4, **kwargs)[source]

Transform data to bytes using pickle.dumps and pickle.loads to retrieve it back.

DEFAULT_ENCODING: str | None = None
dumps(value)[source]

Serialize the received value using pickle.dumps.

Parameters:

value – obj

Returns:

bytes

loads(value)[source]

Deserialize value using pickle.loads.

Parameters:

value – bytes

Returns:

obj

JsonSerializer

class aiocache.serializers.JsonSerializer(*args, encoding=<object object>, **kwargs)[source]

Transform data to json string with json.dumps and json.loads to retrieve it back. Check https://docs.python.org/3/library/json.html#py-to-json-table for how types are converted.

ujson will be used by default if available. Be careful with differences between built in json module and ujson:

  • ujson dumps supports bytes while json doesn’t

  • ujson and json outputs may differ sometimes

dumps(value)[source]

Serialize the received value using json.dumps.

Parameters:

value – dict

Returns:

str

loads(value)[source]

Deserialize value using json.loads.

Parameters:

value – str

Returns:

output of json.loads.

MsgPackSerializer

In case the current serializers are not covering your needs, you can always define your custom serializer as shown in examples/serializer_class.py:

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

You can also use marshmallow as your serializer (examples/marshmallow_serializer_class.py):

 1import random
 2import string
 3import asyncio
 4from typing import Any
 5
 6from marshmallow import fields, Schema, post_load
 7
 8from aiocache import Cache
 9from aiocache.serializers import BaseSerializer
10
11
12class RandomModel:
13    MY_CONSTANT = "CONSTANT"
14
15    def __init__(self, int_type=None, str_type=None, dict_type=None, list_type=None):
16        self.int_type = int_type or random.randint(1, 10)
17        self.str_type = str_type or random.choice(string.ascii_lowercase)
18        self.dict_type = dict_type or {}
19        self.list_type = list_type or []
20
21    def __eq__(self, obj):
22        return self.__dict__ == obj.__dict__
23
24
25class RandomSchema(Schema):
26    int_type = fields.Integer()
27    str_type = fields.String()
28    dict_type = fields.Dict()
29    list_type = fields.List(fields.Integer())
30
31    @post_load
32    def build_my_type(self, data, **kwargs):
33        return RandomModel(**data)
34
35    class Meta:
36        strict = True
37
38
39class MarshmallowSerializer(BaseSerializer):
40    def __init__(self, *args: Any, **kwargs: Any):
41        super().__init__(*args, **kwargs)
42        self.schema = RandomSchema()
43
44    def dumps(self, value: Any) -> str:
45        return self.schema.dumps(value)
46
47    def loads(self, value: str) -> Any:
48        return self.schema.loads(value)
49
50
51cache = Cache(serializer=MarshmallowSerializer(), namespace="main")
52
53
54async def serializer():
55    model = RandomModel()
56    await cache.set("key", model)
57
58    result = await cache.get("key")
59
60    assert result.int_type == model.int_type
61    assert result.str_type == model.str_type
62    assert result.dict_type == model.dict_type
63    assert result.list_type == model.list_type
64
65
66async def test_serializer():
67    await serializer()
68    await cache.delete("key")
69
70
71if __name__ == "__main__":
72    asyncio.run(test_serializer())

By default cache backends assume they are working with str types. If your custom implementation transform data to bytes, you will need to set the class attribute encoding to None.