Debian Codegraph @

examples/marshmallow_serializer_class.py

raw
1 import random
2 import string
3 import asyncio
4
5 from marshmallow import fields, Schema, post_load
6
7 from aiocache import Cache
8 from aiocache.serializers import BaseSerializer
9
10
11 class RandomModel:
12 MY_CONSTANT = "CONSTANT"
13
14 def __init__(self, int_type=None, str_type=None, dict_type=None, list_type=None):
15 self.int_type = int_type or random.randint(1, 10)
16 self.str_type = str_type or random.choice(string.ascii_lowercase)
17 self.dict_type = dict_type or {}
18 self.list_type = list_type or []
19
20 def __eq__(self, obj):
21 return self.__dict__ == obj.__dict__
22
23
24 class MarshmallowSerializer(Schema, BaseSerializer): # type: ignore[misc]
25 int_type = fields.Integer()
26 str_type = fields.String()
27 dict_type = fields.Dict()
28 list_type = fields.List(fields.Integer())
29
30 # marshmallow Schema class doesn't play nicely with multiple inheritance and won't call
31 # BaseSerializer.__init__
32 encoding = 'utf-8'
33
34 @post_load
35 def build_my_type(self, data, **kwargs):
36 return RandomModel(**data)
37
38 class Meta:
39 strict = True
40
41
42 cache = Cache(serializer=MarshmallowSerializer(), namespace="main")
43
44
45 async def serializer():
46 model = RandomModel()
47 await cache.set("key", model)
48
49 result = await cache.get("key")
50
51 assert result.int_type == model.int_type
52 assert result.str_type == model.str_type
53 assert result.dict_type == model.dict_type
54 assert result.list_type == model.list_type
55
56
57 async def test_serializer():
58 await serializer()
59 await cache.delete("key")
60
61
62 if __name__ == "__main__":
63 asyncio.run(test_serializer())