redis#

class litestar.stores.redis.RedisStore#

Bases: NamespacedStore

Redis based, thread and process safe asynchronous key/value store.

__init__(redis: ~redis.asyncio.client.Redis, namespace: str | None | ~typing.Literal[<_EmptyEnum.EMPTY: 0>] = _EmptyEnum.EMPTY, handle_client_shutdown: bool = False) None#

Initialize RedisStore

Parameters:
  • redis – An redis.asyncio.Redis instance

  • namespace – A key prefix to simulate a namespace in redis. If not given, defaults to LITESTAR. Namespacing can be explicitly disabled by passing None. This will make delete_all() unavailable.

  • handle_client_shutdown – If True, handle the shutdown of the redis instance automatically during the store’s lifespan. Should be set to True unless the shutdown is handled externally

classmethod with_client(url: str = 'redis://localhost:6379', *, db: int | None = None, port: int | None = None, username: str | None = None, password: str | None = None, namespace: str | None | ~typing.Literal[<_EmptyEnum.EMPTY: 0>] = _EmptyEnum.EMPTY) RedisStore#

Initialize a RedisStore instance with a new class:redis.asyncio.Redis instance.

Parameters:
  • url – Redis URL to connect to

  • db – Redis database to use

  • port – Redis port to use

  • username – Redis username to use

  • password – Redis password to use

  • namespace – Virtual key namespace to use

with_namespace(namespace: str) RedisStore#

Return a new RedisStore with a nested virtual key namespace. The current instances namespace will serve as a prefix for the namespace, so it can be considered the parent namespace.

async set(key: str, value: str | bytes, expires_in: int | timedelta | None = None) None#

Set a value.

Parameters:
  • key – Key to associate the value with

  • value – Value to store

  • expires_in – Time in seconds before the key is considered expired

Returns:

None

async get(key: str, renew_for: int | timedelta | None = None) bytes | None#

Get a value.

Parameters:
  • key – Key associated with the value

  • renew_for – If given and the value had an initial expiry time set, renew the expiry time for renew_for seconds. If the value has not been set with an expiry time this is a no-op. Atomicity of this step is guaranteed by using a lua script to execute fetch and renewal. If renew_for is not given, the script will be bypassed so no overhead will occur

Returns:

The value associated with key if it exists and is not expired, else None

async delete(key: str) None#

Delete a value.

If no such key exists, this is a no-op.

Parameters:

key – Key of the value to delete

async delete_all() None#

Delete all stored values in the virtual key namespace.

Raises:

ImproperlyConfiguredException – If no namespace was configured

async exists(key: str) bool#

Check if a given key exists.

async expires_in(key: str) int | None#

Get the time in seconds key expires in. If no such key exists or no expiry time was set, return None.