aiohttp-client-cache

raw JSON →
0.14.3 verified Tue Apr 14 auth: no python

aiohttp-client-cache is an async persistent cache for aiohttp client requests, based on requests-cache. It provides a CachedSession that acts as a drop-in replacement for `aiohttp.ClientSession`, offering various configurable storage backends and cache expiration strategies. The current version is 0.14.3, and it receives regular updates for bug fixes and compatibility.

pip install aiohttp-client-cache
error ModuleNotFoundError: No module named 'aiohttp_client_cache'
cause This error occurs when the 'aiohttp-client-cache' package is not installed in your Python environment.
fix
Install the package using pip: 'pip install aiohttp-client-cache'.
error AttributeError: module 'aiohttp' has no attribute 'ClientSession'
cause This error can occur if there's a circular import or if the 'aiohttp' module is not properly installed.
fix
Ensure that 'aiohttp' is installed correctly and check for circular imports in your code. Also, avoid naming your script 'aiohttp.py' to prevent conflicts.
error ImportError: cannot import name 'CachedSession' from 'aiohttp_client_cache'
cause This error occurs when attempting to import 'CachedSession' from 'aiohttp_client_cache' without the package being installed or due to an incorrect import statement.
fix
Ensure that 'aiohttp-client-cache' is installed and use the correct import statement: 'from aiohttp_client_cache import CachedSession'.
error TypeError: 'NoneType' object is not callable
cause This error can occur if 'CachedSession' is not properly initialized or if there's an issue with the cache backend configuration.
fix
Verify that 'CachedSession' is initialized correctly with a valid cache backend, for example: 'session = CachedSession(cache=SQLiteBackend('demo_cache'))'.
error ValueError: Invalid backend: 'redis'
cause This error occurs when specifying a cache backend that is not installed or supported.
fix
Ensure that the required backend dependencies are installed. For Redis, install the package with the Redis extras: 'pip install aiohttp-client-cache[redis]'.
breaking Upgrading to v0.12.0 or later may invalidate previously cached data due to internal changes. Users should clear their cache or be prepared for a temporary loss of cached responses.
fix Clear existing cache files or databases after updating, or simply allow the cache to repopulate.
breaking Minimum Python version required is 3.9+ since v0.13.0. Earlier Python versions are no longer supported.
fix Upgrade your Python environment to 3.9 or higher.
gotcha Caching behavior is determined by a precedence order: Cache-Control request headers > Cache-Control response headers > per-request expiration > per-URL expiration > per-session expiration. This can lead to unexpected caching if not understood.
fix Refer to the documentation on 'Cache Expiration' and 'Cache-Control' to understand how different expiration settings interact and ensure desired caching behavior.
gotcha By default, `CachedSession` without a specified `cache` backend will use a non-persistent, in-memory cache. Data will be lost when the session or application closes.
fix Always explicitly configure a persistent backend (e.g., `SQLiteBackend`, `RedisBackend`) when you need data to persist across application runs. Example: `CachedSession(cache=SQLiteBackend('my_cache.sqlite'))`.
gotcha By default, only `GET` and `HEAD` HTTP methods and `200` status codes are cached. Requests using other methods (like `POST`) or responses with other status codes will not be cached unless explicitly configured.
fix Use `allowed_methods` and `allowed_codes` parameters in your backend configuration to cache additional methods or status codes. Example: `SQLiteBackend(allowed_methods=('GET', 'POST'), allowed_codes=(200, 404))`.
gotcha The library is an 'early work in progress' and breaking changes should be expected until a 1.0 release.
fix Pin your dependency to a specific minor version and thoroughly test when upgrading to newer minor or patch versions.
pip install aiohttp-client-cache[all]

This example demonstrates basic usage of CachedSession with a SQLite backend. The first request to 'httpbin.org/delay/1' will fetch the data and store it in 'demo_cache.sqlite'. Subsequent requests to the same URL will retrieve the response instantly from the cache. The `response.from_cache` attribute indicates if the response was served from the cache.

import asyncio
from aiohttp_client_cache import CachedSession, SQLiteBackend

async def main():
    # Initialize CachedSession with a SQLite backend
    # 'demo_cache' will be the filename for the SQLite database
    async with CachedSession(cache=SQLiteBackend('demo_cache')) as session:
        print("First request (will be slow...")
        response = await session.get('http://httpbin.org/delay/1')
        print(f"Response from cache: {response.from_cache}, Status: {response.status}")

        print("Second request (should be fast...")
        response = await session.get('http://httpbin.org/delay/1')
        print(f"Response from cache: {response.from_cache}, Status: {response.status}")

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