AioCache

0.12.3 · active · verified Thu Apr 09

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

Install

Imports

Quickstart

This quickstart demonstrates how to initialize and use the Redis backend with `aiocache` using the `Cache` factory. It leverages `async with` for automatic connection management and shows setting and getting a key-value pair. Ensure a Redis server is running and accessible.

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

view raw JSON →