| 1 |
import asyncio |
| 2 |
|
| 3 |
from aiocache import caches, Cache |
| 4 |
from aiocache.serializers import StringSerializer, PickleSerializer |
| 5 |
|
| 6 |
caches.set_config({ |
| 7 |
'default': { |
| 8 |
'cache': "aiocache.SimpleMemoryCache", |
| 9 |
'serializer': { |
| 10 |
'class': "aiocache.serializers.StringSerializer" |
| 11 |
} |
| 12 |
}, |
| 13 |
'redis_alt': { |
| 14 |
'cache': "aiocache.RedisCache", |
| 15 |
'endpoint': "127.0.0.1", |
| 16 |
'port': 6379, |
| 17 |
'timeout': 1, |
| 18 |
'serializer': { |
| 19 |
'class': "aiocache.serializers.PickleSerializer" |
| 20 |
}, |
| 21 |
'plugins': [ |
| 22 |
{'class': "aiocache.plugins.HitMissRatioPlugin"}, |
| 23 |
{'class': "aiocache.plugins.TimingPlugin"} |
| 24 |
] |
| 25 |
} |
| 26 |
}) |
| 27 |
|
| 28 |
|
| 29 |
async def default_cache(): |
| 30 |
cache = caches.get('default') # This always returns the same instance |
| 31 |
await cache.set("key", "value") |
| 32 |
|
| 33 |
assert await cache.get("key") == "value" |
| 34 |
assert isinstance(cache, Cache.MEMORY) |
| 35 |
assert isinstance(cache.serializer, StringSerializer) |
| 36 |
|
| 37 |
|
| 38 |
async def alt_cache(): |
| 39 |
# This generates a new instance every time! You can also use |
| 40 |
# `caches.create("alt", namespace="test", etc...)` to override extra args |
| 41 |
cache = caches.create("redis_alt") |
| 42 |
await cache.set("key", "value") |
| 43 |
|
| 44 |
assert await cache.get("key") == "value" |
| 45 |
assert isinstance(cache, Cache.REDIS) |
| 46 |
assert isinstance(cache.serializer, PickleSerializer) |
| 47 |
assert len(cache.plugins) == 2 |
| 48 |
assert cache.endpoint == "127.0.0.1" |
| 49 |
assert cache.timeout == 1 |
| 50 |
assert cache.port == 6379 |
| 51 |
await cache.close() |
| 52 |
|
| 53 |
|
| 54 |
async def test_alias(): |
| 55 |
await default_cache() |
| 56 |
await alt_cache() |
| 57 |
|
| 58 |
cache = Cache(Cache.REDIS) |
| 59 |
await cache.delete("key") |
| 60 |
await cache.close() |
| 61 |
|
| 62 |
await caches.get("default").close() |
| 63 |
|
| 64 |
|
| 65 |
if __name__ == "__main__": |
| 66 |
asyncio.run(test_alias()) |