acachecontrol
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.
Common errors
-
ModuleNotFoundError: No module named 'acachecontrol'
cause The 'acachecontrol' package is not installed in the Python environment.fixInstall the package using pip: 'pip install acachecontrol'. -
ImportError: cannot import name 'AsyncCache' from 'acachecontrol'
cause The 'AsyncCache' class is not available in the 'acachecontrol' module.fixEnsure you are using the correct import statement: 'from acachecontrol import AsyncCache, AsyncCacheControl'. -
TypeError: 'NoneType' object is not subscriptable
cause Attempting to access elements of a 'None' object, possibly due to a failed request or uninitialized cache.fixCheck if the response or cache object is 'None' before accessing its elements. -
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.fixfrom acachecontrol import AsyncCache, AsyncCacheControl cache_instance = AsyncCache() session = AsyncCacheControl(cache=cache_instance) -
NameError: name 'AsyncCacheControl' is not defined
cause The AsyncCacheControl class was used without being imported first from the 'acachecontrol' library.fixfrom acachecontrol import AsyncCacheControl
Warnings
- 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.
- 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.
- 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.
- 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.
Install
-
pip install acachecontrol
Imports
- AsyncCache
from acachecontrol import AsyncCache
- AsyncCacheControl
from acachecontrol import AsyncCacheControl
Quickstart
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())