redisent package

redisent.errors module

exception redisent.errors.RedisError(message: str, base_exception: Optional[Exception] = None, related_command: Optional[str] = None, extra_attrs: Optional[Mapping[str, Any]] = None)[source]

Exception class for Redisent-raised errors

Exceptions of this type will be raised for almost any errors encountered within redisent

This class also offers the :py:func`redisent.errors.RedisError.dump` method which can be used to build a verbose blurb about the error and available context

Build a new RedisError exception with optionally provided contextual details

Parameters
  • message – the error message

  • base_exception – an optional base exception related to this one

  • related_command – if available, the related op_name / Redis command that raised this error (otherwise this will be “N/A”)

  • extra_attrs – optional mapping of related values at the time of the exception being raised

property is_connection_error: bool

Indicates if the underlying error was related to a connection failure

If base_exception is an instance of redis.exceptions.ConnectionError, this will return True

__init__(message: str, base_exception: Optional[Exception] = None, related_command: Optional[str] = None, extra_attrs: Optional[Mapping[str, Any]] = None) None[source]

Build a new RedisError exception with optionally provided contextual details

Parameters
  • message – the error message

  • base_exception – an optional base exception related to this one

  • related_command – if available, the related op_name / Redis command that raised this error (otherwise this will be “N/A”)

  • extra_attrs – optional mapping of related values at the time of the exception being raised

message: str

Error Message

base_exception: Optional[Exception]

Optional base Exception raise prior to this error

related_command: Optional[str]

The Redis command or op_name that caused this error (if available)

extra_attrs: Mapping[str, Any] = {}

Mapping of optional contextual attributes related to this error

dump() str[source]

Helper method for building a verbose textual representation of the error and any available context at the time of the exception being raised

redisent.helpers module

class redisent.helpers.RedisentHelper(redis_pool: redis.connection.ConnectionPool, use_redis: Optional[redis.client.Redis] = None)[source]

Simple ctor method for building RedisentHelper instance from a given RedisPoolType

Parameters
  • redis_pool – Redis connection pool helper should use

  • use_redis – primarily for testing, this instance of one of the redis or redislite classes in the type redisent.common.RedisType. if provided, the RedisentHelper.get_connection() method will return it instead of building a new one with the provided redis_pool (which is ignored)

classmethod handle_decode_attempt(result_value, use_encoding: Optional[str] = None, decode_handler: Optional[Callable[[Any], Optional[Any]]] = None)[source]

Internal handler for attempting to intelligently decode any discovered redisent.models.RedisEntry instances found

Parameters
  • result_value – the result to attempt to decode

  • use_encoding – if provided, indicates the results should be decoded using the provided encoding (generally utf-8)

  • decode_handler – optional callback that will be called when attempting to decode response

classmethod decode_entries(use_encoding: Optional[str] = None, first_handler: Optional[Callable] = None, final_handler: Optional[Callable] = None)[source]

Decorator used for automatically attempting to decode the returned value of a method using the static method handle_decode_attempt

This is helpful for automatically returning redisent.models.RedisEntry instances and / or the opportunity to interact with the results via the two Callable arguments first_handler and final_handler.

If provided, the first_handler is used first, prior to attempting to using the handle_decode_attempt static method. Finally, if provided, the final_handler will be called prior to passing the possibly decoded response back to the caller.

Parameters
  • use_encoding – if provided, indicates the results should be decoded using the provided encoding (generally utf-8)

  • first_handler – first callback handler to invoke __prior__ to attempting to decode the result

  • final_handler – final callback handler to invoke __after__ attempting to decode the result

get_connection(strict_client: bool = False) redis.client.Redis[source]

Synchronous method for creating a new Redis connection which will return a connected redis.Redis or redis.StrictRedis instance, based on the provided strict_client value.

The caller is responsible for all management of the connection life-cycle including closing the connection when no longer needed.

Parameters

strict_client – if specified return an instance of redis.StrictRedis. By default an configured instance of redis.Redis will be returned

__init__(redis_pool: redis.connection.ConnectionPool, use_redis: Optional[redis.client.Redis] = None) None[source]

Simple ctor method for building RedisentHelper instance from a given RedisPoolType

Parameters
  • redis_pool – Redis connection pool helper should use

  • use_redis – primarily for testing, this instance of one of the redis or redislite classes in the type redisent.common.RedisType. if provided, the RedisentHelper.get_connection() method will return it instead of building a new one with the provided redis_pool (which is ignored)

redis_pool: redis.connection.ConnectionPool
use_redis: Optional[redis.client.Redis]
classmethod build_pool(redis_uri: str) redis.connection.ConnectionPool[source]

Build a RedisPoolType instance from the given Redis URI

This method uses redis.connection.ConnectionPool.from_url under the hood to build the connection pool

Parameters

redis_uri – URI of Redis server (will be prefixed with redis:// if not present)

wrapped_redis(op_name: str = None)[source]
keys(use_pattern: Optional[str] = None, redis_id: Optional[str] = None, use_encoding: Optional[str] = None) List[str][source]

Synchronous method responsible for enumerating key values in Redis for hash and non-hash entries alike

If use_pattern and redis_id are not provided, this method will use KEYS(*) to lookup all Redis keys.

Otherwise, if redis_id is provided, a lookup of HKEYS(redis_id) will be done.

Finally, if use_pattern is provided, KEYS(use_pattern) will be used

Parameters
  • use_pattern – if provided, use this value instead of * with KEYS

  • redis_id – if provided, use HKEYS(redis_id) to lookup keys in the hash entry

  • use_encoding – if provided, use this charset to decode bytes response (default is utf-8)

exists(redis_id: str, redis_name: Optional[str] = None) bool[source]

Synchronous method for checking if a given redis_id (and optional redis_name value, if provided) actually exists in Redis

Parameters
  • redis_id – the Redis ID for entry

  • redis_name – if provided, attempt to lookup hashmap based on this value

entry_type(redis_id: str, check_exists: bool = True) Optional[str][source]

Determine the Redis type of the provided redis_id entry

Parameters
  • redis_id – the Redis ID for entry

  • check_exists – if set, use the RedisentHelper.exists() method to validate the entry exists or return None

get(redis_id: str, redis_name: Optional[str] = None, throw_error: bool = True) Optional[Any][source]

Method for fetching Redis entry based on redis_id and an optional redis_name value

If redis_name is also provided, the hash get (HGET) method will be used to fetch the hashmap entry requested

Parameters
  • redis_id – the Redis ID for entry

  • redis_name – if provided, attempt to lookup hashmap based on this value

  • throw_error – if set, a redisent.errors.RedisError exception will be raised if the entry cannot be fetched, otherwise None will be returned

set(redis_id: str, value: Any, redis_name: Optional[str] = None, check_exists_type: bool = True) bool[source]

Method for storing a value in Redis as redis_id and optional redis_name for storing hashmap data

If redis_name is alos provided, this operation will use HSET to create a hashmap. Otherwise SET is used and value must be an instance of one of the supported redisent.common.RedisType types.

Parameters
  • redis_id – the Redis ID for entry

  • value – value to be stored in Redis. If this is not a hashmap, it must be a Redis primitive type of RedisType

  • redis_name – if provided, store this entry as a hashmap using both redis_id and redis_name

Returns

bool indicating if there the value was being set for the first time (i.e. True means it was not previously set)

delete(redis_id: str, redis_name: Optional[str] = None, check_exists: bool = True) Optional[bool][source]

Method for deleting stored Redis entries based on provided redis_id and optional hashmap name redis_name

:param :param redis_id: the Redis ID for entry to remove :param redis_name: if provided, attempt to delete the named entry in the hashmap based on this value :param check_exists: if set, use the RedisentHelper.exists() method to validate the entry exists :returns: bool indicating if the entry was deleted. if check_exists fails, None will be returned

redisent.models module

class redisent.models.RedisEntry[source]

Base dataclass that should be inherited from with additional dataclasses.field() s for each attribute the entry will store.

All RedisEntry instances must define a unique-to-Redis value for redis_id. If the entry is going to be stored as a hash-map, the class must also define a value for redis_name.

If the redis_name attribute is set, at a high level, the storing and fetching of values looks like this:

In [1]: import pickle
   ...: import redis
   ...:
   ...: # Setup some dummy values
   ...: redis_id = 'blah'
   ...: redis_name = 'entry_one'
   ...: ent_values = {'value_one': 1, 'value_two': 2}

In [2]: # Pickle the dictionary data to bytes
   ...: ent_pickle = pickle.dumps(ent_values)

In [3]: # Build Redis connection
   ...: conn = redis.StrictRedis('localhost')

In [4]: # Store them
   ...: conn.hset(redis_id, redis_name, ent_pickle)
Out[4]: 1

In [5]: # Fetch back the raw pickled values
   ...: res_raw = conn.hget(redis_id, redis_name)

In [6]: # Assert they equal the values we set (obviously this should be true)
   ...: assert res_raw == ent_pickle

In [7]: # Now, decode the response
   ...: res_values = pickle.loads(res_raw)

In [8]: # And finally assert that "res_values" is the same as the original "ent_values"
   ...: assert res_values == ent_values

In [9]: res_values
Out[9]: {'value_one': 1, 'value_two': 2}
redis_id: ClassVar[str]
redis_name: Optional[str] = False
dump(include_internal_fields: bool = False) str[source]

Helper for dumping a textual representation of a particular redisent.models.RedisEntry instance

classmethod get_entry_fields(include_internal_fields: bool = False) Mapping[str, dataclasses.Field][source]

Class method used for building a list of strings for each field name, based on the provided filering attributes

Parameters

include_internal_fields – if set, include internal fields which are used by redisent only (any marked with metadata attribute internal_field)

property is_hashmap: bool

Property helper to determine if this entry is a hash-map or not

This is simply determined by if redis_name is set or not.

classmethod load_dict(redis_id: Optional[str] = None, redis_name: Optional[str] = None, **ent_kwargs) redisent.models.RedisEntry[source]

Class method for loading a RedisEntry from a provided dictionary of values

Parameters
  • redis_id – unique Redis ID for entry

  • redis_name – unique Redis hashmap name (if entity is stored as a hashmap, this is required)

  • ent_kwargs – keyword arguments used to build entry values

as_dict(include_internal_fields: bool = False, use_json: bool = False, ignore_invalid: bool = True) Mapping[str, Any][source]

Return a mapping representing this entry by making use of dataclasses.asdict() along with optionally excluding any Redis-related (or internal) fields.

By default no internal or redis fields (i.e. redis_id or redis_name) are returned

Parameters

include_internal_fields – if set, include internal fields which are used by redisent only (any marked with metadata attribute internal_field)

classmethod decode_entry(entry_bytes, use_redis_id: Optional[str] = None, use_redis_name: Optional[str] = None)[source]

Class method for attempting to build a redisent.models.RedisEntry instance from the provided bytes value entry_bytes

Under the hood, this makes use of pickle.loads() and redisent.models.RedisEntry.load_dict to actually attempt to build the entry while catching any related exceptions and propagating them as redisent.errors.RedisError exceptions.

classmethod encode_entry(entry: redisent.models.RedisEntry, as_mapping: Optional[bool] = None) bytes[source]

Class method for encoding a given redisent.models.RedisEntry instance as bytes using the pickle.dumps() method.

Parameters
store(helper: redisent.helpers.RedisentHelper) bool[source]

Blocking / synchronous method for storing this entry in Redis, using the provided redisent.helpers.RedisentHelper instance.

This method will do the actual encoding using the RedisEntry.encode_entry() method as well as make use of the provided helper redisent.helpers.RedisentHelper.wrapped_redis() (actually, this method makes use of the redisent.helpers.RedisentHelper.wrapped_redis()) context manager for storing the entry in Redis.

Parameters

helper – configured instance of redisent.helpers.RedisentHelper to be used for storing entry

classmethod fetch_all(helper: redisent.helpers.RedisentHelper, redis_id: str, check_exists: bool = True) Mapping[str, redisent.models.RedisEntry][source]

Method for fetching all entries for a given hashmap from Redis, using the provided redisent.helpers.RedisentHelper instance.

Under the hood, this method will call the redisent.helpers.RedisentHelper.keys() method to enumerate all of the hashmap entry keys and iteratively fetch them and return a mapping of hash keys to RedisEntry instances.

Parameters
  • helper – configured instance of redisent.helpers.RedisentHelper to be used for fetching entries

  • redis_id – unique Redis ID for hash map entries

  • check_exists – if set, check first that there is an existing Redis entry to fetch. If not, a RedisEntry is raised

classmethod fetch(helper: redisent.helpers.RedisentHelper, redis_id: str, redis_name: Optional[str] = None, check_exists: bool = True) redisent.models.RedisEntry[source]

Method for fetching entries from Redis, using the provided redisent.helpers.RedisentHelper instance.

This method will do the actual decoding using the RedisEntry.decode_entry() method after fetching the bytes value from Redis using the helper-provided redisent.helpers.RedisentHelper.wrapped_redis() (actually, this method makes use of the redisent.helpers.RedisentHelper.wrapped_redis()) context manager for actually fetching from Redis.

Parameters
  • helper – configured instance of redisent.helpers.RedisentHelper to be used for storing entry

  • redis_id – unique Redis ID for entry

  • redis_name – unique Redis hashmap name (if entity is stored as a hashmap, this is required)

  • check_exists – if set, check first that there is an existing Redis entry to fetch. If not, a RedisEntry is raised

delete(helper: redisent.helpers.RedisentHelper, check_exists: bool = True) Optional[bool][source]

Method responsible for actually deleting a RedisEntry from Redis

Parameters
  • helper – configured instance of redisent.helpers.RedisentHelper to be used to delete the entry

  • check_exists – if set, check first that there is an existing Redis entry for this instance

__init__() None