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
:
- 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", 'host': "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:
1import asyncio
2
3import redis.asyncio as redis
4
5from aiocache import caches, Cache
6from aiocache.serializers import StringSerializer, PickleSerializer
7
8caches.set_config({
9 'default': {
10 'cache': "aiocache.SimpleMemoryCache",
11 'serializer': {
12 'class': "aiocache.serializers.StringSerializer"
13 }
14 },
15 'redis_alt': {
16 'cache': "aiocache.RedisCache",
17 "host": "127.0.0.1",
18 'port': 6379,
19 "socket_connect_timeout": 1,
20 'serializer': {
21 'class': "aiocache.serializers.PickleSerializer"
22 },
23 'plugins': [
24 {'class': "aiocache.plugins.HitMissRatioPlugin"},
25 {'class': "aiocache.plugins.TimingPlugin"}
26 ]
27 }
28})
29
30
31async def default_cache():
32 cache = caches.get('default') # This always returns the same instance
33 await cache.set("key", "value")
34
35 assert await cache.get("key") == "value"
36 assert isinstance(cache, Cache.MEMORY)
37 assert isinstance(cache.serializer, StringSerializer)
38
39
40async def alt_cache():
41 # This generates a new instance every time! You can also use
42 # `caches.create("alt", namespace="test", etc...)` to override extra args
43 cache = caches.create("redis_alt")
44 await cache.set("key", "value")
45
46 assert await cache.get("key") == "value"
47 assert isinstance(cache, Cache.REDIS)
48 assert isinstance(cache.serializer, PickleSerializer)
49 assert len(cache.plugins) == 2
50 connection_args = cache.client.connection_pool.connection_kwargs
51 assert connection_args["host"] == "127.0.0.1"
52 assert connection_args["socket_connect_timeout"] == 1
53 assert connection_args["port"] == 6379
54 await cache.close()
55
56
57async def test_alias():
58 await default_cache()
59 await alt_cache()
60
61 cache = Cache(Cache.REDIS, client=redis.Redis())
62 await cache.delete("key")
63 await cache.close()
64
65 await caches.get("default").close()
66
67
68if __name__ == "__main__":
69 asyncio.run(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.
- caches.add(alias: str, config: Dict[str, object]) 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
- caches.get(alias: str) object ¶
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
- caches.create(alias, **kwargs)¶
Create a new cache.
You can use kwargs to pass extra parameters to configure the cache.
- Parameters:
alias – alias to pull configuration from
- Returns:
New cache instance