API Reference

This section covers all the public interfaces of requests-cache.

Sessions

class requests_cache.session.CachedSession(cache_name='http_cache', backend=None, expire_after=- 1, urls_expire_after=None, allowable_codes=(200,), allowable_methods=('GET', 'HEAD'), filter_fn=None, old_data_on_error=False, cache_control=False, **kwargs)[source]

Bases: requests_cache.session.CacheMixin, requests.sessions.Session

Class that extends requests.Session with caching features.

See individual backend classes for additional backend-specific arguments. Also see User Guide for more details and examples on how the following arguments affect cache behavior.

Parameters
  • cache_name (str) – Cache prefix or namespace, depending on backend

  • backend (Union[str, BaseCache, Type[BaseCache], None]) – Cache backend name, class, or instance; name may be one of ['sqlite', 'mongodb', 'gridfs', 'redis', 'dynamodb', 'memory'].

  • expire_after (Union[None, int, float, str, datetime, timedelta]) – Time after which cached items will expire

  • urls_expire_after (Optional[Dict[str, Union[None, int, float, str, datetime, timedelta]]]) – Expiration times to apply for different URL patterns

  • allowable_codes (Iterable[int]) – Only cache responses with one of these codes

  • allowable_methods (Iterable[str]) – Cache only responses for one of these HTTP methods

  • include_get_headers – Make request headers part of the cache key

  • ignored_parameters – List of request parameters to be excluded from the cache key

  • filter_fn (Optional[Callable]) – function that takes a aiohttp.ClientResponse object and returns a boolean indicating whether or not that response should be cached. Will be applied to both new and previously cached responses.

  • old_data_on_error (bool) – Return stale cache data if a new request raises an exception

  • cache_control (bool) – Use Cache-Control request and response headers

cache_disabled()

Context manager for temporary disabling the cache

Warning

This method is not thread-safe.

Example

>>> s = CachedSession()
>>> with s.cache_disabled():
...     s.get('http://httpbin.org/ip')
remove_expired_responses(expire_after=None)

Remove expired responses from the cache, optionally with revalidation

Parameters

expire_after (Union[None, int, float, str, datetime, timedelta]) – A new expiration time used to revalidate the cache

request(method, url, params=None, data=None, json=None, expire_after=None, **kwargs)

This method prepares and sends a request while automatically performing any necessary caching operations. This will be called by any other method-specific requests functions (get, post, etc.). This does not include prepared requests, which will still be cached via send().

See requests.Session.request() for parameters. Additional parameters:

Parameters

expire_after (Union[None, int, float, str, datetime, timedelta]) – Expiration time to set only for this request; see details below. Overrides CachedSession.expire_after. Accepts all the same values as CachedSession.expire_after except for None; use -1 to disable expiration on a per-request basis.

Return type

Union[Response, CachedResponse]

Returns

Either a new or cached response

Order of operations: For reference, a request will pass through the following methods:

  1. requests.get()/requests.Session.get() or other method-specific functions (optional)

  2. CachedSession.request()

  3. requests.Session.request()

  4. CachedSession.send()

  5. BaseCache.get_response()

  6. requests.Session.send() (if not previously cached)

  7. BaseCache.save_response() (if not previously cached)

send(request, **kwargs)

Send a prepared request, with caching. See request() for notes on behavior.

Return type

Union[Response, CachedResponse]

class requests_cache.session.CacheMixin(cache_name='http_cache', backend=None, expire_after=- 1, urls_expire_after=None, allowable_codes=(200,), allowable_methods=('GET', 'HEAD'), filter_fn=None, old_data_on_error=False, cache_control=False, **kwargs)[source]

Mixin class that extends requests.Session with caching features. See CachedSession for usage information.

Patching

Utilities for patching requests.

Warning

These functions are not thread-safe. Use CachedSession directly if you want to use caching in a multi-threaded environment.

requests_cache.patcher.clear()[source]

Clear the currently installed cache (if any)

requests_cache.patcher.disabled()[source]

Context manager for temporarily disabling caching for all requests functions

Example

>>> with requests_cache.disabled():
...     requests.get('http://httpbin.org/get')
requests_cache.patcher.enabled(*args, **kwargs)[source]

Context manager for temporarily enabling caching for all requests functions

Accepts the same arguments as install_cache().

Example

>>> with requests_cache.enabled('cache_db'):
...     requests.get('http://httpbin.org/get')
requests_cache.patcher.get_cache()[source]

Get the internal cache object from the currently installed CachedSession (if any)

Return type

Optional[BaseCache]

requests_cache.patcher.install_cache(cache_name='http_cache', backend=None, expire_after=-1, urls_expire_after=None, allowable_codes=(200, ), allowable_methods=('GET', 'HEAD'), filter_fn=None, old_data_on_error=False, session_factory=<class 'requests_cache.session.CachedSession'>, **kwargs)[source]

Install the cache for all requests functions by monkey-patching requests.Session

Example

>>> requests_cache.install_cache('demo_cache')

Accepts all the same parameters as CachedSession. Additional parameters:

Parameters

session_factory (Type[Session]) – Session class to use. It must inherit from either CachedSession or CacheMixin

requests_cache.patcher.is_installed()[source]

Indicate whether or not requests-cache is currently installed

Return type

bool

requests_cache.patcher.remove_expired_responses(expire_after=None)[source]

Remove expired responses from the cache, optionally with revalidation

Parameters

expire_after (Union[None, int, float, str, datetime, timedelta]) – A new expiration time used to revalidate the cache

requests_cache.patcher.uninstall_cache()[source]

Disable the cache by restoring the original requests.Session

Cache Backends

Models

Serializers

Utilities