acachecontrol

raw JSON →
0.3.7 verified Wed Apr 15 auth: no python

acachecontrol is an asynchronous library that provides Cache-Control functionality for aiohttp. It aims to bridge the gap left by `requests-cache` for the popular `aiohttp` client, allowing developers to easily implement HTTP caching. The library is currently at version 0.3.7 and receives updates to address issues and maintain compatibility with its dependencies.

pip install acachecontrol
error ModuleNotFoundError: No module named 'acachecontrol'
cause The 'acachecontrol' package is not installed in the Python environment.
fix
Install the package using pip: 'pip install acachecontrol'.
error ImportError: cannot import name 'AsyncCache' from 'acachecontrol'
cause The 'AsyncCache' class is not available in the 'acachecontrol' module.
fix
Ensure you are using the correct import statement: 'from acachecontrol import AsyncCache, AsyncCacheControl'.
error TypeError: 'NoneType' object is not subscriptable
cause Attempting to access elements of a 'None' object, possibly due to a failed request or uninitialized cache.
fix
Check if the response or cache object is 'None' before accessing its elements.
error TypeError: AsyncCacheControl.__init__ missing 1 required positional argument: 'cache'
cause The AsyncCacheControl class requires an instance of AsyncCache (or a compatible cache object) to be passed via the 'cache' keyword argument during initialization.
fix
from acachecontrol import AsyncCache, AsyncCacheControl cache_instance = AsyncCache() session = AsyncCacheControl(cache=cache_instance)
error NameError: name 'AsyncCacheControl' is not defined
cause The AsyncCacheControl class was used without being imported first from the 'acachecontrol' library.
fix
from acachecontrol import AsyncCacheControl
breaking Version 0.3.6 updated the minimum required `aiohttp` version to `>=3.10.2`. Using `acachecontrol` with older `aiohttp` versions may lead to compatibility issues or errors.
fix Ensure `aiohttp` is installed with version `>=3.10.2`. Update `aiohttp` if an older version is present: `pip install --upgrade aiohttp`.
gotcha When implementing a custom cache backend for `AsyncCache`, it must fully adhere to the `OrderedDict` interface, including methods like `__contains__`, `__len__`, `__getitem__`, `__setitem__`, `get`, `pop`, `popitem`, and `move_to_end`. Incomplete implementations can cause unexpected runtime errors or incorrect caching behavior.
fix Refer to the `CustomCacheBackend` example in the official documentation or GitHub README for a complete list of required methods and their expected behavior.
gotcha Versions of `acachecontrol` prior to `0.3.4` could fail if a `Cache-Control` header contained a `max-age` directive that was not a valid number. This would result in parsing errors and prevent caching.
fix Upgrade to `acachecontrol>=0.3.4` to handle non-numeric `max-age` values gracefully. Additionally, ensure upstream services provide valid integer values for `max-age`.
gotcha A default request timeout issue was fixed in version `0.3.3`. Users of older versions might experience requests hanging or unexpectedly timing out under certain conditions.
fix Upgrade to `acachecontrol>=0.3.3` to resolve this issue. Consider explicitly setting timeouts on `aiohttp.ClientSession` for fine-grained control if needed.

This quickstart demonstrates how to use `acachecontrol` to cache HTTP GET requests made with `aiohttp`. The first request to `http://example.com` will fetch the content, and subsequent requests within the cache's validity period will be served from the cache without making a new network request to the origin server. The `from_cache` attribute on the response indicates if it was served from cache. You can configure `AsyncCache` with different backends if needed.

import asyncio
from acachecontrol import AsyncCache, AsyncCacheControl

async def main():
    # Initialize AsyncCache, default configuration uses an in-memory dictionary
    cache = AsyncCache()

    # Use AsyncCacheControl to wrap an aiohttp ClientSession
    async with AsyncCacheControl(cache=cache) as cached_session:
        print("First request (should fetch):")
        async with cached_session.get('http://example.com') as resp:
            text_data = await resp.text()
            print(f"Status: {resp.status}, From cache: {getattr(resp, 'from_cache', False)}")
            # print(text_data[:100]) # Print first 100 chars for brevity

        print("\nSecond request (should be cached):")
        async with cached_session.get('http://example.com') as resp:
            text_data = await resp.text()
            print(f"Status: {resp.status}, From cache: {getattr(resp, 'from_cache', False)}")
            # print(text_data[:100]) # Print first 100 chars for brevity

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