Plugins

Plugins can be used to enrich the behavior of the cache. By default all caches are configured without any plugin but can add new ones in the constructor or after initializing the cache class:

>>> from aiocache import SimpleMemoryCache
>>> from aiocache.plugins import TimingPlugin
cache = SimpleMemoryCache(plugins=[HitMissRatioPlugin()])
cache.plugins += [TimingPlugin()]

You can define your custom plugin by inheriting from BasePlugin and overriding the needed methods (the overrides NEED to be async). All commands have pre_<command_name> and post_<command_name> hooks.

Warning

Both pre and post hooks are executed awaiting the coroutine. If you perform expensive operations with the hooks, you will add more latency to the command being executed and thus, there are more probabilities of raising a timeout error.

A complete example of using plugins:

 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
53
54
55
56
57
58
59
import asyncio
import random
import logging

from aiocache import SimpleMemoryCache
from aiocache.plugins import HitMissRatioPlugin, TimingPlugin, BasePlugin


logger = logging.getLogger(__name__)


class MyCustomPlugin(BasePlugin):

    async def pre_set(self, *args, **kwargs):
        logger.info("I'm the pre_set hook being called with %s %s" % (args, kwargs))

    async def post_set(self, *args, **kwargs):
        logger.info("I'm the post_set hook being called with %s %s" % (args, kwargs))


cache = SimpleMemoryCache(
    plugins=[HitMissRatioPlugin(), TimingPlugin(), MyCustomPlugin()],
    namespace="main")


async def run():
    await cache.set("a", "1")
    await cache.set("b", "2")
    await cache.set("c", "3")
    await cache.set("d", "4")

    possible_keys = ["a", "b", "c", "d", "e", "f"]

    for t in range(1000):
        await cache.get(random.choice(possible_keys))

    assert cache.hit_miss_ratio["hit_ratio"] > 0.5
    assert cache.hit_miss_ratio["total"] == 1000

    assert cache.profiling["get_min"] > 0
    assert cache.profiling["set_min"] > 0
    assert cache.profiling["get_max"] > 0
    assert cache.profiling["set_max"] > 0

    print(cache.hit_miss_ratio)
    print(cache.profiling)


def test_run():
    loop = asyncio.get_event_loop()
    loop.run_until_complete(run())
    loop.run_until_complete(cache.delete("a"))
    loop.run_until_complete(cache.delete("b"))
    loop.run_until_complete(cache.delete("c"))
    loop.run_until_complete(cache.delete("d"))


if __name__ == "__main__":
    test_run()

BasePlugin

class aiocache.plugins.BasePlugin[source]
classmethod add_hook(func, hooks)[source]
do_nothing(*args, **kwargs)[source]
post_add(*args, **kwargs)
post_clear(*args, **kwargs)
post_delete(*args, **kwargs)
post_exists(*args, **kwargs)
post_expire(*args, **kwargs)
post_get(*args, **kwargs)
post_increment(*args, **kwargs)
post_multi_get(*args, **kwargs)
post_multi_set(*args, **kwargs)
post_raw(*args, **kwargs)
post_set(*args, **kwargs)
pre_add(*args, **kwargs)
pre_clear(*args, **kwargs)
pre_delete(*args, **kwargs)
pre_exists(*args, **kwargs)
pre_expire(*args, **kwargs)
pre_get(*args, **kwargs)
pre_increment(*args, **kwargs)
pre_multi_get(*args, **kwargs)
pre_multi_set(*args, **kwargs)
pre_raw(*args, **kwargs)
pre_set(*args, **kwargs)

TimingPlugin

class aiocache.plugins.TimingPlugin[source]

Calculates average, min and max times each command takes. The data is saved in the cache class as a dict attribute called profiling. For example, to access the average time of the operation get, you can do cache.profiling['get_avg']

post_add(client, *args, took=0, **kwargs)
post_clear(client, *args, took=0, **kwargs)
post_delete(client, *args, took=0, **kwargs)
post_exists(client, *args, took=0, **kwargs)
post_expire(client, *args, took=0, **kwargs)
post_get(client, *args, took=0, **kwargs)
post_increment(client, *args, took=0, **kwargs)
post_multi_get(client, *args, took=0, **kwargs)
post_multi_set(client, *args, took=0, **kwargs)
post_raw(client, *args, took=0, **kwargs)
post_set(client, *args, took=0, **kwargs)
classmethod save_time(method)[source]

HitMissRatioPlugin

class aiocache.plugins.HitMissRatioPlugin[source]

Calculates the ratio of hits the cache has. The data is saved in the cache class as a dict attribute called hit_miss_ratio. For example, to access the hit ratio of the cache, you can do cache.hit_miss_ratio['hit_ratio']. It also provides the “total” and “hits” keys.

post_get(client, key, took=0, ret=None)[source]
post_multi_get(client, keys, took=0, ret=None)[source]