Debian Codegraph @

examples/plugins.py

raw
1 import asyncio
2 import random
3 import logging
4
5 from aiocache import Cache
6 from aiocache.plugins import HitMissRatioPlugin, TimingPlugin, BasePlugin
7
8
9 logger = logging.getLogger(__name__)
10
11
12 class MyCustomPlugin(BasePlugin):
13
14 async def pre_set(self, *args, **kwargs):
15 logger.info("I'm the pre_set hook being called with %s %s" % (args, kwargs))
16
17 async def post_set(self, *args, **kwargs):
18 logger.info("I'm the post_set hook being called with %s %s" % (args, kwargs))
19
20
21 cache = Cache(
22 plugins=[HitMissRatioPlugin(), TimingPlugin(), MyCustomPlugin()],
23 namespace="main")
24
25
26 async def run():
27 await cache.set("a", "1")
28 await cache.set("b", "2")
29 await cache.set("c", "3")
30 await cache.set("d", "4")
31
32 possible_keys = ["a", "b", "c", "d", "e", "f"]
33
34 for t in range(1000):
35 await cache.get(random.choice(possible_keys))
36
37 assert cache.hit_miss_ratio["hit_ratio"] > 0.5
38 assert cache.hit_miss_ratio["total"] == 1000
39
40 assert cache.profiling["get_min"] > 0
41 assert cache.profiling["set_min"] > 0
42 assert cache.profiling["get_max"] > 0
43 assert cache.profiling["set_max"] > 0
44
45 print(cache.hit_miss_ratio)
46 print(cache.profiling)
47
48
49 async def test_run():
50 await run()
51 await cache.delete("a")
52 await cache.delete("b")
53 await cache.delete("c")
54 await cache.delete("d")
55
56
57 if __name__ == "__main__":
58 asyncio.run(test_run())