Welcome to aiocache’s documentation!

Installing

  • pip install aiocache

  • pip install aiocache[redis]

  • pip install aiocache[memcached]

  • pip install aiocache[redis,memcached]

Usage

Using a cache is as simple as

>>> import asyncio
>>> from aiocache import Cache
>>> cache = Cache()
>>> with asyncio.Runner() as runner:
>>>     runner.run(cache.set("key", "value"))
True
>>>     runner.run(cache.get("key"))
'value'

Here we are using the SimpleMemoryCache but you can use any other listed in Caches. All caches contain the same minimum interface which consists on the following functions:

  • add: Only adds key/value if key does not exist. Otherwise raises ValueError.

  • get: Retrieve value identified by key.

  • set: Sets key/value.

  • multi_get: Retrieves multiple key/values.

  • multi_set: Sets multiple key/values.

  • exists: Returns True if key exists False otherwise.

  • increment: Increment the value stored in the given key.

  • delete: Deletes key and returns number of deleted items.

  • clear: Clears the items stored.

  • raw: Executes the specified command using the underlying client.

You can also setup cache aliases like in Django settings:

 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())

In examples folder you can check different use cases:

Contents

Indices and tables