Redis#

../_images/redis.png

Redis is an in-memory data store with on-disk persistence. It offers a high-performace cache that scales exceptionally well, making it an ideal choice for larger applications.

Persistence#

Redis operates on data in memory, and by default also persists data to snapshots on disk. This is optimized for performance, with a minor risk of data loss, and is usually the best configuration for a cache. If you need different behavior, the frequency and type of persistence can be customized or disabled entirely. See Redis Persistence for details.

Connection Options#

The Redis backend accepts any keyword arguments for redis.client.Redis:

>>> backend = RedisCache(host='192.168.1.63', port=6379)
>>> session = CachedSession('http_cache', backend=backend)

API Reference#

RedisCache

Redis cache backend

RedisDict

A dictionary-like interface for Redis operations.

RedisHashDict

A dictionary-like interface for operations on a single Redis hash

class requests_cache.backends.redis.RedisCache(namespace='http_cache', connection=None, **kwargs)[source]#

Bases: requests_cache.backends.base.BaseCache

Redis cache backend

Parameters
  • namespace – Redis namespace

  • connection (Optional[Redis]) – Redis connection instance to use instead of creating a new one

  • kwargs – Additional keyword arguments for redis.client.Redis

bulk_delete(keys)#

Remove multiple responses and their associated redirects from the cache

Parameters

keys (Iterable[str]) –

clear()#

Delete all items from the cache

contains(key=None, request=None, url=None)#

Check if the specified request is cached

Parameters
create_key(request=None, **kwargs)#

Create a normalized cache key from a request object

Parameters

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

Return type

str

delete(*keys, expired=False, invalid=False, requests=None, urls=None)#

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)

  • 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)

delete_url(url, method='GET', **kwargs)#
Parameters
  • url (str) –

  • method (str) –

delete_urls(urls, method='GET', **kwargs)#
Parameters
filter(valid=True, expired=True, invalid=False)#

Get responses from the cache, with optional filters

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)

Return type

Iterator[CachedResponse]

get_response(key, default=None)#

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)#
Parameters

key (str) –

Return type

bool

has_url(url, method='GET', **kwargs)#
Parameters
  • url (str) –

  • method (str) –

Return type

bool

keys(check_expiry=False)#
Parameters

check_expiry (bool) –

Return type

Iterator[str]

remove_expired_responses(expire_after=None)#
Parameters

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

reset_expiration(expire_after=None)#

Set a new expiration value on existing cache items

Parameters

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

response_count(check_expiry=False)#
Parameters

check_expiry (bool) –

Return type

int

save_response(response, cache_key=None, expires=None)#

Save a response to the cache

Parameters
update(other)#

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)#
Parameters

check_expiry (bool) –

Return type

Iterator[CachedResponse]

class requests_cache.backends.redis.RedisDict(namespace, collection_name=None, connection=None, **kwargs)[source]#

Bases: requests_cache.backends.base.BaseStorage

A dictionary-like interface for Redis operations.

Notes:
  • All keys will be encoded as bytes, and all values will be serialized

  • Supports TTL

Parameters
bulk_delete(keys)[source]#

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

Parameters

keys (Iterable[str]) –

clear() None.  Remove all items from D.[source]#
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[source]#
keys() a set-like object providing a view on D's keys[source]#
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[source]#
class requests_cache.backends.redis.RedisHashDict(namespace='http_cache', collection_name=None, connection=None, **kwargs)[source]#

Bases: requests_cache.backends.base.BaseStorage

A dictionary-like interface for operations on a single Redis hash

Notes:
  • All keys will be encoded as bytes, and all values will be serialized

  • Items will be stored in a hash named namespace:collection_name

Parameters
bulk_delete(keys)[source]#

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

Parameters

keys (Iterable[str]) –

clear() None.  Remove all items from D.[source]#
get(k[, d]) D[k] if k in D, else d.  d defaults to None.#
items()[source]#

Get all (key, value) pairs in the hash

keys() a set-like object providing a view on D's keys[source]#
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()[source]#

Get all values in the hash