CacheControl

0.14.4 · active · verified Sat Mar 28

CacheControl provides an HTTP caching layer for the popular `requests` library, mimicking the caching algorithms found in `httplib2`. It aims to make `requests` sessions thread-safe and efficient by persisting HTTP responses according to cache-control headers. The library is actively maintained, with frequent updates addressing Python version compatibility, bug fixes, and serialization improvements.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up `CacheControl` with `requests` using a persistent `FileCache`. The first `GET` request will fetch data from the network and cache it. Subsequent requests to the same URL, if cacheable, will be served from the local cache.

import requests
from cachecontrol import CacheControl
from cachecontrol.caches.file_cache import FileCache

# Create a standard requests session
sess = requests.Session()

# Wrap the session with CacheControl using a FileCache for persistent storage
# Replace '.web_cache' with your desired cache directory
cached_sess = CacheControl(sess, cache=FileCache('.web_cache'))

# Make a request - the response will be cached if HTTP headers allow
response = cached_sess.get('https://httpbin.org/cache/60')
print(f"First request status: {response.status_code}")
print(f"From cache (should be False): {getattr(response, 'from_cache', False)}")

# Make the same request again - it should now be served from cache
response = cached_sess.get('https://httpbin.org/cache/60')
print(f"Second request status: {response.status_code}")
print(f"From cache (should be True): {getattr(response, 'from_cache', False)}")

# Clean up the cache directory (optional for a real app)
# import shutil
# shutil.rmtree('.web_cache', ignore_errors=True)

view raw JSON →