asyncache

0.3.1 · active · verified Sat Apr 11

asyncache is a Python library providing helpers to easily integrate `cachetools` caching strategies with asynchronous Python code, specifically designed for `asyncio` applications. It allows developers to decorate `async` functions to transparently cache their results. The current version is 0.3.1, released in November 2022, and it appears to be actively maintained through issues and pull requests, though new releases are infrequent.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use the `@cached` decorator from `asyncache` with a `TTLCache` from `cachetools` to cache the results of an asynchronous function. It shows cache hits and misses, and how Time-To-Live (TTL) expiration works.

import asyncio
from asyncache import cached
from cachetools import TTLCache

# A simple async function that simulates an expensive operation
async def fetch_user_data(user_id: int) -> dict:
    print(f"Fetching data for user {user_id} from database...")
    await asyncio.sleep(1) # Simulate I/O delay
    return {"id": user_id, "name": f"User {user_id} Name"}

# Cache the results of the async function using TTLCache from cachetools
# The cache will hold up to 1024 items, with each entry expiring after 60 seconds.
@cached(TTLCache(maxsize=1024, ttl=60))
async def get_user_cached(user_id: int) -> dict:
    return await fetch_user_data(user_id)

async def main():
    print("--- First call (cache miss) ---")
    user1 = await get_user_cached(1)
    print(f"Result: {user1}\n")

    print("--- Second call (cache hit) ---")
    user1_cached = await get_user_cached(1)
    print(f"Result: {user1_cached}\n")

    print("--- Third call with different ID (cache miss) ---")
    user2 = await get_user_cached(2)
    print(f"Result: {user2}\n")

    print("--- Waiting for TTL to expire (will force a re-fetch) ---")
    await asyncio.sleep(61) # Wait for cache entry to expire

    print("--- Fourth call (cache miss after TTL) ---")
    user1_after_ttl = await get_user_cached(1)
    print(f"Result: {user1_after_ttl}\n")

if __name__ == "__main__":
    asyncio.run(main())

view raw JSON →