General Usage#

There are two main ways of using requests-cache:


CachedSession can be used as a drop-in replacement for requests.Session. Basic usage looks like this:

>>> from requests_cache import CachedSession
>>> session = CachedSession()
>>> session.get('')

Any requests.Session method can be used (but see Cached HTTP Methods section for options):

>>> session.request('GET', '')
>>> session.head('')

Caching can be temporarily disabled for the session with CachedSession.cache_disabled():

>>> with session.cache_disabled():
...     session.get('')

The best way to clean up your cache is through Expiration settings, but you can also clear out everything at once with BaseCache.clear():

>>> session.cache.clear()


In some situations, it may not be possible or convenient to manage your own session object. In those cases, you can use install_cache() to add caching to all requests functions:

>>> import requests
>>> import requests_cache
>>> requests_cache.install_cache()
>>> requests.get('')

As well as session methods:

>>> session = requests.Session()
>>> session.get('')

install_cache() accepts all the same parameters as CachedSession:

>>> requests_cache.install_cache(expire_after=360, allowable_methods=('GET', 'POST'))

It can be temporarily enabled():

>>> with requests_cache.enabled():
...     requests.get('')  # Will be cached

Or temporarily disabled():

>>> requests_cache.install_cache()
>>> with requests_cache.disabled():
...     requests.get('')  # Will not be cached

Or completely removed with uninstall_cache():

>>> requests_cache.uninstall_cache()
>>> requests.get('')

You can also clear out all responses in the cache with clear(), and check if requests-cache is currently installed with is_installed().

Patching Limitations & Potential Issues#

Like any other utility that uses monkey-patching, there are some scenarios where you won’t want to use install_cache():

  • When using other libraries that patch requests.Session

  • In a multi-threaded or multiprocess application

  • In a library that will be imported by other libraries or applications

  • In a larger application that makes requests in several different modules, where it may not be obvious what is and isn’t being cached

In any of these cases, consider using CachedSession, the enabled() contextmanager, or Cached URLs.