(redis)=
Redis is an in-memory data store with on-disk persistence.
Redis offers a high-performace cache that scales exceptionally well, making it an ideal choice for larger applications, especially those that make a large volume of concurrent requests.
Initialize your session with a {py:class}.RedisCache
instance:
>>> from requests_cache import CachedSession, RedisCache >>> session = CachedSession(backend=RedisCache())
Or by alias:
>>> session = CachedSession(backend='redis')
This backend accepts any keyword arguments for {py:class}redis.client.Redis
:
>>> backend = RedisCache(host='192.168.1.63', port=6379) >>> session = CachedSession('http_cache', backend=backend)
Or you can pass an existing Redis
object:
>>> from redis import Redis >>> connection = Redis(host='192.168.1.63', port=6379) >>> backend = RedisCache(connection=connection)) >>> session = CachedSession('http_cache', backend=backend)
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.
Redis natively supports TTL on a per-key basis, and can automatically remove expired responses from the cache. This will be set by by default, according to normal {ref}expiration settings <expiration>
.
Expired items are not removed immediately, but will never be returned from the cache. See Redis: EXPIRE docs for more details.
If you intend to reuse expired responses, e.g. with {ref}conditional-requests
or stale_if_error
, you can disable this behavior with the ttl
argument:
>>> backend = RedisCache(ttl=False)
If you can't easily set up your own Redis server, another option is redislite. It contains its own lightweight, embedded Redis database, and can be used as a drop-in replacement for redis-py. Usage example:
>>> from redislite import Redis >>> from requests_cache import CachedSession, RedisCache >>> backend = RedisCache(connection=Redis()) >>> session = CachedSession(backend=backend)