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 SimpleMemoryCache
>>> from aiocache.serializers import PickleSerializer
cache = SimpleMemoryCache(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.SimpleMemoryCachebecause 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]
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
dumpsmethod.If you want to keep python types, use
PickleSerializer.JsonSerializermay also be useful to keep type of simple python types.
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¶
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
MsgPackSerializer¶
- class aiocache.serializers.MsgPackSerializer(*args, use_list=True, **kwargs)[source]¶
Transform data to bytes using msgpack.dumps and msgpack.loads to retrieve it back. You need to have
msgpackinstalled in order to be able to use this serializer.- Parameters:
encoding – str. Can be used to change encoding param for
msg.loadsmethod. Default is utf-8.use_list – bool. Can be used to change use_list param for
msgpack.loadsmethod. Default is True.
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
4from glide import GlideClientConfiguration, NodeAddress
5
6from aiocache import ValkeyCache
7from aiocache.serializers import BaseSerializer
8
9addresses = [NodeAddress("localhost", 6379)]
10config = GlideClientConfiguration(addresses=addresses, database_id=0)
11
12
13class CompressionSerializer(BaseSerializer):
14
15 # This is needed because zlib works with bytes.
16 # this way the underlying backend knows how to
17 # store/retrieve values
18 DEFAULT_ENCODING = None
19
20 def dumps(self, value):
21 print("I've received:\n{}".format(value))
22 compressed = zlib.compress(value.encode())
23 print("But I'm storing:\n{}".format(compressed))
24 return compressed
25
26 def loads(self, value):
27 print("I've retrieved:\n{}".format(value))
28 decompressed = zlib.decompress(value).decode()
29 print("But I'm returning:\n{}".format(decompressed))
30 return decompressed
31
32
33async def serializer(cache):
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 )
42 await cache.set("key", text)
43 print("-----------------------------------")
44 real_value = await cache.get("key")
45 compressed_value = await cache.raw("get", "main:key")
46 assert len(compressed_value) < len(real_value.encode())
47
48
49async def test_serializer():
50 async with ValkeyCache(
51 config, namespace="main", serializer=CompressionSerializer()
52 ) as cache:
53 await serializer(cache)
54 await cache.delete("key")
55 await cache.close()
56
57
58if __name__ == "__main__":
59 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 SimpleMemoryCache
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 = SimpleMemoryCache(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.