acachecontrol

0.3.7 · active · verified Wed Apr 15

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

Warnings

Install

Imports

Quickstart

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())

view raw JSON →