Base

Base classes for all cache backends

BaseCache

Base class for cache backends.

BaseStorage

Base class for client-agnostic storage implementations.

DictStorage

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

class requests_cache.backends.base.BaseCache(cache_name='http_cache', **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:

  • Saving and retrieving responses

  • Managing redirect history

  • Convenience methods for general cache info

  • Dict-like wrapper methods around the underlying storage

Notes:

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

  • serializer – Serializer name or instance

  • kwargs – Additional backend-specific keyword arguments

clear()[source]

Delete all items from the cache

close()[source]

Close any open backend connections

contains(key=None, request=None, url=None, verify=True)[source]

Check if the specified request is cached

Parameters:
  • key (Optional[str]) – Check for a specific cache key

  • request (Union[Request, PreparedRequest, CachedRequest, None]) – Check for a matching request, according to current request matching settings

  • url (Optional[str]) – Check for a matching GET request with the specified URL

  • verify (bool) – Check for requests with or without SSL verification

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

Create a normalized cache key from a request object

Parameters:
Return type:

str

property db_path: str | Path

Path to the cache database file.

Raises:

NotImplementedError – For backends that do not use a file-based database.

delete(*keys, expired=False, invalid=False, older_than=None, requests=None, urls=None, verify=True)[source]

Remove responses from the cache according one or more conditions.

Parameters:
  • keys (str) – Remove responses with these cache keys

  • expired (bool) – Remove all expired responses

  • invalid (bool) – Remove all invalid responses (that can’t be deserialized with current settings)

  • older_than (Union[None, int, float, str, datetime, timedelta]) – Remove responses older than this value, relative to response.created_at

  • requests (Optional[Iterable[Union[Request, PreparedRequest, CachedRequest]]]) – Remove matching responses, according to current request matching settings

  • urls (Optional[Iterable[str]]) – Remove matching GET requests for the specified URL(s)

  • verify (bool) – Set to False to remove responses without SSL verification

filter(valid=True, expired=True, invalid=False, older_than=None)[source]

Get responses from the cache, with optional filters for which responses to include:

Parameters:
  • valid (bool) – Include valid and unexpired responses; set to False to get only expired/invalid/old responses

  • expired (bool) – Include expired responses

  • invalid (bool) – Include invalid responses (as an empty CachedResponse)

  • older_than (Union[None, int, float, str, datetime, timedelta]) – Get responses older than this value, relative to response.created_at

Return type:

Iterator[CachedResponse]

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]

recreate_keys()[source]

Recreate cache keys for all previously cached responses

remove_expired_responses(expire_after=None)[source]
Parameters:

expire_after (Union[None, int, float, str, datetime, timedelta])

reset_expiration(expire_after=None)[source]

Set a new expiration value to set on existing cache items

Parameters:

expire_after (Union[None, int, float, str, datetime, timedelta]) – New expiration value, relative to the current time

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 (Response) – Response to save

  • expires (Optional[datetime]) – Absolute expiration time for this response

update(other)[source]

Update this cache with the contents of another cache

Parameters:

other (BaseCache)

urls(**kwargs)[source]

Get all unique cached URLs. Optionally takes keyword arguments for filter().

Return type:

List[str]

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

Bases: MutableMapping[KT, VT], ABC

Base class for client-agnostic storage implementations. Notes:

  • 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, which are handled by BaseCache subclasses.

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

Parameters:
  • serializer (Union[str, SerializerPipeline, Stage, None]) – Custom serializer that provides loads and dumps methods. If not provided, values will be written as-is.

  • decode_content (bool) – Decode response body JSON or text into a human-readable format

  • kwargs – Additional backend-specific keyword arguments

bulk_delete(keys)[source]

Delete multiple keys from the cache, without raising errors for missing keys.

This is a naive, generic implementation that subclasses should override with a more efficient backend-specific implementation, if possible.

Parameters:

keys (Iterable[TypeVar(KT)])

clear() None.  Remove all items from D.
close()[source]

Close any open backend connections

deserialize(key, value)[source]

Deserialize a value, if a serializer is available.

If deserialization fails (usually due to a value saved in an older requests-cache version), None will be returned.

Parameters:

value (TypeVar(VT))

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.

serialize(value)[source]

Serialize a value, if a serializer is available

Parameters:

value (TypeVar(VT))

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.keys(): 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: UserDict, 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, generic implementation that subclasses should override with a more efficient backend-specific implementation, if possible.

Parameters:

keys (Iterable[TypeVar(KT)])

clear() None.  Remove all items from D.
close()

Close any open backend connections

copy()
deserialize(key, value)

Deserialize a value, if a serializer is available.

If deserialization fails (usually due to a value saved in an older requests-cache version), None will be returned.

Parameters:

value (TypeVar(VT))

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.

serialize(value)

Serialize a value, if a serializer is available

Parameters:

value (TypeVar(VT))

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.keys(): 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