File: serializer_function.py

package info (click to toggle)
aiocache 0.12.3-2
  • links: PTS
  • area: main
  • in suites: forky, sid, trixie
  • size: 692 kB
  • sloc: python: 5,044; makefile: 221; sh: 7
file content (52 lines) | stat: -rw-r--r-- 1,078 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import asyncio
import json

from marshmallow import Schema, fields, post_load
from aiocache import Cache


class MyType:
    def __init__(self, x, y):
        self.x = x
        self.y = y


class MyTypeSchema(Schema):
    x = fields.Number()
    y = fields.Number()

    @post_load
    def build_object(self, data, **kwargs):
        return MyType(data['x'], data['y'])


def dumps(value):
    return MyTypeSchema().dumps(value)


def loads(value):
    return MyTypeSchema().loads(value)


cache = Cache(Cache.REDIS, namespace="main")


async def serializer_function():
    await cache.set("key", MyType(1, 2), dumps_fn=dumps)

    obj = await cache.get("key", loads_fn=loads)

    assert obj.x == 1
    assert obj.y == 2
    assert await cache.get("key") == json.loads(('{"y": 2.0, "x": 1.0}'))
    assert json.loads(await cache.raw("get", "main:key")) == {"y": 2.0, "x": 1.0}


async def test_serializer_function():
    await serializer_function()
    await cache.delete("key")
    await cache.close()


if __name__ == "__main__":
    asyncio.run(test_serializer_function())