(general)=
play-circle General UsageThere are two main ways of using requests-cache:
.CachedSession to send your requestsrequests using {py:func}.install_cache(){py:class}.CachedSession can be used as a drop-in replacement for {py:class}requests.Session. Basic usage looks like this:
>>> from requests_cache import CachedSession >>> session = CachedSession() >>> session.get('http://httpbin.org/get')
Any {py:class}requests.Session method can be used (but see {ref}http-methods section for options):
>>> session.request('GET', 'http://httpbin.org/get') >>> session.head('http://httpbin.org/get')
Caching can be temporarily disabled for the session with {py:meth}.CachedSession.cache_disabled:
>>> with session.cache_disabled(): ... session.get('http://httpbin.org/get')
The best way to clean up your cache is through {ref}expiration settings, but you can also clear out everything at once with {py:meth}.BaseCache.clear:
>>> session.cache.clear()
(patching)=
In some situations, it may not be possible or convenient to manage your own session object. In those cases, you can use {py:func}.install_cache to add caching to all requests functions:
>>> import requests >>> import requests_cache >>> requests_cache.install_cache() >>> requests.get('http://httpbin.org/get')
As well as session methods:
>>> session = requests.Session() >>> session.get('http://httpbin.org/get')
{py:func}.install_cache accepts all the same parameters as {py:class}.CachedSession:
>>> requests_cache.install_cache(expire_after=360, allowable_methods=('GET', 'POST'))
It can be temporarily {py:func}.enabled:
>>> with requests_cache.enabled(): ... requests.get('http://httpbin.org/get') # Will be cached
Or temporarily {py:func}.disabled:
>>> requests_cache.install_cache() >>> with requests_cache.disabled(): ... requests.get('http://httpbin.org/get') # Will not be cached
Or completely removed with {py:func}.uninstall_cache:
>>> requests_cache.uninstall_cache() >>> requests.get('http://httpbin.org/get')
You can also clear out all responses in the cache with {py:func}.clear, and check if requests-cache is currently installed with {py:func}.is_installed.
(monkeypatch-issues)=
There are some scenarios where patching requests with {py:func}.install_cache is not ideal:
requests.SessionIn these cases, consider using {py:class}.CachedSession instead.
(settings)=
There are a number of settings that affect cache behavior, which are covered in more detail in the following sections:
expirationfilteringmatchingThese can all be passed as keyword arguments to {py:class}.CachedSession or {py:func}.install_cache. When using a session object, these can also be safely modified at any time via {py:attr}.CachedSession.settings. For example:
>>> from requests_cache import CachedSession >>> session = CachedSession() >>> session.settings.expire_after = 360 >>> session.settings.stale_if_error = True
Note that this does not include backend and serializer settings, which cannot be changed after initialization.