aiohttp-client-cache
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.
Warnings
- 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.
- breaking Minimum Python version required is 3.9+ since v0.13.0. Earlier Python versions are no longer supported.
- 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.
- 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.
- 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.
- gotcha The library is an 'early work in progress' and breaking changes should be expected until a 1.0 release.
Install
-
pip install aiohttp-client-cache -
pip install aiohttp-client-cache[all]
Imports
- CachedSession
from aiohttp_client_cache import CachedSession
- SQLiteBackend
from aiohttp_client_cache import SQLiteBackend
- ClientSession (when caching is desired)
from aiohttp_client_cache import CachedSession
- aiohttp-cache (for client-side caching)
from aiohttp_client_cache import CachedSession
Quickstart
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())