Requests Cache

1.3.1 · active · verified Wed Apr 01

Requests-cache is a persistent HTTP cache that provides an easy way to get better performance with the popular Python `requests` library. It's particularly useful for web scraping, consuming REST APIs, or dealing with slow or rate-limited sites. It supports various storage backends like SQLite, Redis, MongoDB, DynamoDB, and the filesystem, offering flexible expiration strategies. The current version is 1.3.1, and it maintains an active release cadence.

Warnings

Install

Imports

Quickstart

The most common and recommended way to use `requests-cache` is by creating a `CachedSession` instance, which acts as a direct replacement for `requests.Session`. This example demonstrates making a request, observing it being cached, and then retrieving it from the cache instantly on a subsequent call. It also shows how to clear the cache.

import requests_cache
import requests

# Use CachedSession as a drop-in replacement for requests.Session
session = requests_cache.CachedSession('demo_cache', expire_after=3600)

# Make a request; it will be cached
response1 = session.get('https://httpbin.org/delay/1')
print(f"First request (from cache: {response1.from_cache}): {response1.status_code}")

# Make the same request again; it will be loaded from cache instantly
response2 = session.get('https://httpbin.org/delay/1')
print(f"Second request (from cache: {response2.from_cache}): {response2.status_code}")

# Example for global patching (less recommended for complex apps)
# requests_cache.install_cache('global_cache', expire_after=3600)
# response3 = requests.get('https://httpbin.org/delay/1')
# print(f"Third request (from cache: {getattr(response3, 'from_cache', False)}): {response3.status_code}")

# Clear the cache
session.cache.clear()
print("Cache cleared.")

view raw JSON →