Package: requests-cache
Summaryrequests-cacheis a persistent HTTP cache that provides an easy way to get better
performance with the pythonrequestslibrary.Complete project documentation can be found atrequests-cache.readthedocs.io.Features🍰Ease of use:Keep using therequestslibrary you're already familiar with. Add caching
with adrop-in replacementforrequests.Session, orinstall globallyto add transparent caching to allrequestsfunctions.🚀Performance:Get sub-millisecond response times for cached responses. When they expire, you
still save time withconditional requests.💾Persistence:Works with severalstorage backendsincluding SQLite, Redis, MongoDB, and DynamoDB; or save responses as plain JSON files, YAML,
and more🕗Expiration:UseCache-Controland other standard HTTP headers, define your own expiration schedule, keep your cache clutter-free
with backends that natively support TTL, or any combination of strategies⚙️Customization:Works out of the box with zero config, but with a robust set of features for
configuring and extending the library to suit your needs🧩Compatibility:Can be combined with otherpopular libraries based on requestsQuickstartFirst, install with pip:pipinstallrequests-cacheThen, userequests_cache.CachedSessionto make your requests. It behaves like a normalrequests.Session,
but with caching behavior.To illustrate, we'll call an endpoint that adds a delay of 1 second, simulating a slow or
rate-limited website.This takes 1 minute:importrequestssession=requests.Session()foriinrange(60):session.get('https://httpbin.org/delay/1')This takes 1 second:importrequests_cachesession=requests_cache.CachedSession('demo_cache')foriinrange(60):session.get('https://httpbin.org/delay/1')With caching, the response will be fetched once, saved todemo_cache.sqlite, and subsequent
requests will return the cached response near-instantly.PatchingIf you don't want to manage a session object, or just want to quickly test it out in your
application without modifying any code, requests-cache can also be installed globally, and all
requests will be transparently cached:importrequestsimportrequests_cacherequests_cache.install_cache('demo_cache')requests.get('https://httpbin.org/delay/1')Headers and ExpirationBy default, requests-cache will keep cached responses indefinitely. In most cases, you will want to
use one of the two following strategies to balance cache freshness and performance:Define exactly how long to keep responses:Use theexpire_afterparameter to set a fixed expiration time for all new responses:fromrequests_cacheimportCachedSessionfromdatetimeimporttimedelta# Keep responses for 360 secondssession=CachedSession('demo_cache',expire_after=360)# Or use timedelta objects to specify other units of timesession=CachedSession('demo_cache',expire_after=timedelta(hours=1))SeeExpirationfor
more features and settings.Use Cache-Control headers:Use thecache_controlparameter to enable automatic expiration based onCache-Controland other
standard HTTP headers sent by the server:fromrequests_cacheimportCachedSessionsession=CachedSession('demo_cache',cache_control=True)SeeCache Headersfor more details.SettingsThe default settings work well for most use cases, but there are plenty of ways to customize
caching behavior when needed. Here is a quick example of some of the options available:fromdatetimeimporttimedeltafromrequests_cacheimportCachedSessionsession=CachedSession('demo_cache',use_cache_dir=True,# Save files in the default user cache dircache_control=True,# Use Cache-Control response headers for expiration, if availableexpire_after=timedelta(days=1),# Otherwise expire responses after one dayallowable_codes=[200,400],# Cache 400 responses as a solemn reminder of your failuresallowable_methods=['GET','POST'],# Cache whatever HTTP methods you wantignored_parameters=['api_key'],# Don't match this request param, and redact if from the cachematch_headers=['Accept-Language'],# Cache a different response per languagestale_if_error=True,# In case of request errors, use stale cache data if possible)Next StepsTo find out more about what you can do with requests-cache, see:User GuideExamplesAPI ReferenceProject Info