Configuration

The caches module allows to setup cache configurations and then use them either using an alias or retrieving the config explicitly. To set the config, call caches.set_config:

classmethod caches.set_config(config)

Set (override) the default config for cache aliases from a dict-like structure. The structure is the following:

{
    'default': {
        'cache': "aiocache.SimpleMemoryCache",
        'serializer': {
            'class': "aiocache.serializers.StringSerializer"
        }
    },
    'redis_alt': {
        'cache': "aiocache.RedisCache",
        'endpoint': "127.0.0.10",
        'port': 6378,
        'serializer': {
            'class': "aiocache.serializers.PickleSerializer"
        },
        'plugins': [
            {'class': "aiocache.plugins.HitMissRatioPlugin"},
            {'class': "aiocache.plugins.TimingPlugin"}
        ]
    }
}

‘default’ key must always exist when passing a new config. Default configuration is:

{
    'default': {
        'cache': "aiocache.SimpleMemoryCache",
        'serializer': {
            'class': "aiocache.serializers.StringSerializer"
        }
    }
}

You can set your own classes there. The class params accept both str and class types.

All keys in the config are optional, if they are not passed the defaults for the specified class will be used.

If a config key already exists, it will be updated with the new values.

To retrieve a copy of the current config, you can use caches.get_config or caches.get_alias_config for an alias config.

Next snippet shows an example usage:

 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
60
61
62
63
64
65
66
67
import asyncio

from aiocache import caches, SimpleMemoryCache, RedisCache
from aiocache.serializers import StringSerializer, PickleSerializer

caches.set_config({
    'default': {
        'cache': "aiocache.SimpleMemoryCache",
        'serializer': {
            'class': "aiocache.serializers.StringSerializer"
        }
    },
    'redis_alt': {
        'cache': "aiocache.RedisCache",
        'endpoint': "127.0.0.1",
        'port': 6379,
        'timeout': 1,
        'serializer': {
            'class': "aiocache.serializers.PickleSerializer"
        },
        'plugins': [
            {'class': "aiocache.plugins.HitMissRatioPlugin"},
            {'class': "aiocache.plugins.TimingPlugin"}
        ]
    }
})


async def default_cache():
    cache = caches.get('default')   # This always returns the same instance
    await cache.set("key", "value")

    assert await cache.get("key") == "value"
    assert isinstance(cache, SimpleMemoryCache)
    assert isinstance(cache.serializer, StringSerializer)


async def alt_cache():
    # This generates a new instance every time! You can also use `caches.create('alt')`
    # or even `caches.create('alt', namespace="test", etc...)` to override extra args
    cache = caches.create(**caches.get_alias_config('redis_alt'))
    await cache.set("key", "value")

    assert await cache.get("key") == "value"
    assert isinstance(cache, RedisCache)
    assert isinstance(cache.serializer, PickleSerializer)
    assert len(cache.plugins) == 2
    assert cache.endpoint == "127.0.0.1"
    assert cache.timeout == 1
    assert cache.port == 6379
    await cache.close()


def test_alias():
    loop = asyncio.get_event_loop()
    loop.run_until_complete(default_cache())
    loop.run_until_complete(alt_cache())

    cache = RedisCache()
    loop.run_until_complete(cache.delete("key"))
    loop.run_until_complete(cache.close())

    loop.run_until_complete(caches.get('default').close())


if __name__ == "__main__":
    test_alias()

When you do caches.get('alias_name'), the cache instance is built lazily the first time. Next accesses will return the same instance. If instead of reusing the same instance, you need a new one every time, use caches.create('alias_name'). One of the advantages of caches.create is that it accepts extra args that then are passed to the cache constructor. This way you can override args like namespace, endpoint, etc.

classmethod caches.add(alias: str, config: dict) → None

Add a cache to the current config. If the key already exists, it will overwrite it:

>>> caches.add('default', {
        'cache': "aiocache.SimpleMemoryCache",
        'serializer': {
            'class': "aiocache.serializers.StringSerializer"
        }
    })
Parameters:
  • alias – The alias for the cache
  • config – Mapping containing the cache configuration
classmethod caches.get(alias: str)

Retrieve cache identified by alias. Will return always the same instance

If the cache was not instantiated yet, it will do it lazily the first time this is called.

Parameters:alias – str cache alias
Returns:cache instance
classmethod caches.create(alias=None, cache=None, **kwargs)

Create a new cache. Either alias or cache params are required. You can use kwargs to pass extra parameters to configure the cache.

Deprecated since version 0.11.0: Only creating a cache passing an alias is supported. If you want to create a cache passing explicit cache and kwargs use aiocache.Cache.

Parameters:
  • alias – str alias to pull configuration from
  • cache – str or class cache class to use for creating the new cache (when no alias is used)
Returns:

New cache instance