AioCache
aiocache is a multi-backend asynchronous cache library for Python, providing support for Redis, Memcached, and in-memory caching. It integrates well with asyncio applications. The current version is 0.12.3, and it receives regular patch updates, with minor versions released periodically.
Warnings
- breaking Breaking change: aiocache migrated from `aioredis` to the official `redis` Python library. Existing code using `aioredis` specific APIs or directly importing `aioredis` backend classes will break.
- breaking Breaking change: The `SimpleMemoryBackend` (and `SimpleMemoryCache`) is no longer a global singleton. Each instance now has its own isolated cache.
- deprecated Deprecated `loop` parameters have been removed from most methods and constructors, including `Cache.create()`. Passing an explicit `loop` will now raise an error.
- gotcha Typing support was removed in `v0.12.1` due to issues and is planned to be re-introduced in `v1.0`. Users expecting comprehensive type hints will find them missing or causing unresolvable errors.
Install
-
pip install aiocache[redis,memcached] -
pip install aiocache
Imports
- Cache
from aiocache import Cache
- cached
from aiocache.cached import cached
- RedisCache
from aiocache.backends.redis import RedisCache
- MemcachedCache
from aiocache.backends.memcached import MemcachedCache
- SimpleMemoryCache
from aiocache.backends.memory import SimpleMemoryCache
Quickstart
import asyncio
import os
from aiocache import Cache
async def main():
# Configure Redis cache using environment variables or fallbacks
redis_endpoint = os.environ.get('REDIS_ENDPOINT', 'localhost')
redis_port = int(os.environ.get('REDIS_PORT', '6379'))
# Use async with for proper resource management (auto-closes connection)
async with Cache(Cache.REDIS, endpoint=redis_endpoint, port=redis_port) as cache:
key = "my_async_key"
value = "hello from aiocache"
ttl_seconds = 60
print(f"Setting '{key}' = '{value}' with TTL {ttl_seconds}s")
await cache.set(key, value, ttl=ttl_seconds)
retrieved_value = await cache.get(key)
print(f"Retrieved value for '{key}': {retrieved_value}")
if retrieved_value == value:
print("Value successfully cached and retrieved!")
else:
print("Cache retrieval failed.")
if __name__ == '__main__':
# Ensure Redis server is running at REDIS_ENDPOINT:REDIS_PORT
# e.g., docker run --name some-redis -p 6379:6379 -d redis
asyncio.run(main())