| 1 |
import asyncio |
| 2 |
import json |
| 3 |
|
| 4 |
from marshmallow import Schema, fields, post_load |
| 5 |
from aiocache import Cache |
| 6 |
|
| 7 |
|
| 8 |
class MyType: |
| 9 |
def __init__(self, x, y): |
| 10 |
self.x = x |
| 11 |
self.y = y |
| 12 |
|
| 13 |
|
| 14 |
class MyTypeSchema(Schema): |
| 15 |
x = fields.Number() |
| 16 |
y = fields.Number() |
| 17 |
|
| 18 |
@post_load |
| 19 |
def build_object(self, data, **kwargs): |
| 20 |
return MyType(data['x'], data['y']) |
| 21 |
|
| 22 |
|
| 23 |
def dumps(value): |
| 24 |
return MyTypeSchema().dumps(value) |
| 25 |
|
| 26 |
|
| 27 |
def loads(value): |
| 28 |
return MyTypeSchema().loads(value) |
| 29 |
|
| 30 |
|
| 31 |
cache = Cache(Cache.REDIS, namespace="main") |
| 32 |
|
| 33 |
|
| 34 |
async def serializer_function(): |
| 35 |
await cache.set("key", MyType(1, 2), dumps_fn=dumps) |
| 36 |
|
| 37 |
obj = await cache.get("key", loads_fn=loads) |
| 38 |
|
| 39 |
assert obj.x == 1 |
| 40 |
assert obj.y == 2 |
| 41 |
assert await cache.get("key") == json.loads(('{"y": 2.0, "x": 1.0}')) |
| 42 |
assert json.loads(await cache.raw("get", "main:key")) == {"y": 2.0, "x": 1.0} |
| 43 |
|
| 44 |
|
| 45 |
async def test_serializer_function(): |
| 46 |
await serializer_function() |
| 47 |
await cache.delete("key") |
| 48 |
await cache.close() |
| 49 |
|
| 50 |
|
| 51 |
if __name__ == "__main__": |
| 52 |
asyncio.run(test_serializer_function()) |