Base

Base classes for all cache backends.

BaseCache

Base class for cache backends.

BaseStorage

Base class for backend storage implementations.

DictStorage

A basic dict wrapper class for non-persistent, in-memory storage

class requests_cache.backends.base.BaseCache(cache_name='http_cache', match_headers=False, ignored_parameters=None, key_fn=None, **kwargs)[source]

Bases: object

Base class for cache backends. Can be used as a non-persistent, in-memory cache.

This manages higher-level cache operations, including:

  • Cache expiration

  • Generating cache keys

  • Managing redirect history

  • Convenience methods for general cache info

Lower-level storage operations are handled by BaseStorage.

To extend this with your own custom backend, see Custom Backends.

Parameters
bulk_delete(keys)[source]

Remove multiple responses and their associated redirects from the cache

Parameters

keys (Iterable[str]) –

clear()[source]

Delete all items from the cache

create_key(request=None, **kwargs)[source]

Create a normalized cache key from a request object

Parameters

request (Union[Request, PreparedRequest, CachedRequest, None]) –

Return type

str

delete(key)[source]

Delete a response or redirect from the cache, as well any associated redirect history

Parameters

key (str) –

delete_url(url, method='GET', **kwargs)[source]

Delete a cached response for the specified request

Parameters
  • url (str) –

  • method (str) –

delete_urls(urls, method='GET', **kwargs)[source]

Delete all cached responses for the specified requests

Parameters
get_response(key, default=None)[source]

Retrieve a response from the cache, if it exists

Parameters
  • key (str) – Cache key for the response

  • default – Value to return if key is not in the cache

Return type

Optional[CachedResponse]

has_key(key)[source]

Returns True if key is in the cache

Parameters

key (str) –

Return type

bool

has_url(url, method='GET', **kwargs)[source]

Returns True if the specified request is cached

Parameters
  • url (str) –

  • method (str) –

Return type

bool

keys(check_expiry=False)[source]

Get all cache keys for redirects and valid responses combined

Return type

Iterator[str]

remove_expired_responses(expire_after=None)[source]

Remove expired and invalid 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

response_count(check_expiry=False)[source]

Get the number of responses in the cache, excluding invalid (unusable) responses. Can also optionally exclude expired responses.

Return type

int

save_response(response, cache_key=None, expires=None)[source]

Save a response to the cache

Parameters
  • cache_key (Optional[str]) – Cache key for this response; will otherwise be generated based on request

  • response (Union[Response, CachedResponse]) – response to save

  • expire_after – Time in seconds until this cache item should expire

  • expires (Optional[datetime]) –

update(other)[source]

Update this cache with the contents of another cache

Parameters

other (BaseCache) –

property urls

Get all URLs currently in the cache (excluding redirects)

Return type

Iterator[str]

values(check_expiry=False)[source]

Get all valid response objects from the cache

Return type

Iterator[CachedResponse]

class requests_cache.backends.base.BaseStorage(serializer=None, **kwargs)[source]

Bases: collections.abc.MutableMapping, abc.ABC

Base class for backend storage implementations. This provides a common dictionary-like interface for the underlying storage operations (create, read, update, delete). One BaseStorage instance corresponds to a single table/hash/collection, or whatever the backend-specific equivalent may be.

BaseStorage subclasses contain no behavior specific to requests or caching, which are handled by BaseCache.

BaseStorage also contains a serializer module or instance (defaulting to pickle), which determines how CachedResponse objects are saved internally. See Serializers for details.

Parameters
  • serializer – Custom serializer that provides loads and dumps methods

  • kwargs – Additional serializer or backend-specific keyword arguments

bulk_delete(keys)[source]

Delete multiple keys from the cache, without raising errors for missing keys. This is a naive implementation that subclasses should override with a more efficient backend-specific implementation, if possible.

Parameters

keys (Iterable[str]) –

clear() None.  Remove all items from D.
get(k[, d]) D[k] if k in D, else d.  d defaults to None.
items() a set-like object providing a view on D's items
keys() a set-like object providing a view on D's keys
pop(k[, d]) v, remove specified key and return the corresponding value.

If key is not found, d is returned if given, otherwise KeyError is raised.

popitem() (k, v), remove and return some (key, value) pair

as a 2-tuple; but raise KeyError if D is empty.

property serializer
setdefault(k[, d]) D.get(k,d), also set D[k]=d if k not in D
update([E, ]**F) None.  Update D from mapping/iterable E and F.

If E present and has a .keys() method, does: for k in E: D[k] = E[k] If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v In either case, this is followed by: for k, v in F.items(): D[k] = v

values() an object providing a view on D's values
class requests_cache.backends.base.DictStorage(*args, **kwargs)[source]

Bases: collections.UserDict, requests_cache.backends.base.BaseStorage

A basic dict wrapper class for non-persistent, in-memory storage

Note

This is mostly a placeholder for when no other backends are available. For in-memory caching, either SQLiteCache (with use_memory=True) or RedisCache is recommended instead.

bulk_delete(keys)

Delete multiple keys from the cache, without raising errors for missing keys. This is a naive implementation that subclasses should override with a more efficient backend-specific implementation, if possible.

Parameters

keys (Iterable[str]) –

clear() None.  Remove all items from D.
copy()
classmethod fromkeys(iterable, value=None)
get(k[, d]) D[k] if k in D, else d.  d defaults to None.
items() a set-like object providing a view on D's items
keys() a set-like object providing a view on D's keys
pop(k[, d]) v, remove specified key and return the corresponding value.

If key is not found, d is returned if given, otherwise KeyError is raised.

popitem() (k, v), remove and return some (key, value) pair

as a 2-tuple; but raise KeyError if D is empty.

property serializer
setdefault(k[, d]) D.get(k,d), also set D[k]=d if k not in D
update([E, ]**F) None.  Update D from mapping/iterable E and F.

If E present and has a .keys() method, does: for k in E: D[k] = E[k] If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v In either case, this is followed by: for k, v in F.items(): D[k] = v

values() an object providing a view on D's values