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
redisentThis 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
RedisErrorexception 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_exceptionis an instance ofredis.exceptions.ConnectionError, this will returnTrue
- __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
RedisErrorexception 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
The Redis command or
op_namethat caused this error (if available)
redisent.helpers module¶
- class redisent.helpers.RedisentHelper(redis_pool: redis.connection.ConnectionPool, use_redis: Optional[redis.client.Redis] = None)[source]¶
Simple
ctormethod for buildingRedisentHelperinstance from a givenRedisPoolType- Parameters
redis_pool – Redis connection pool helper should use
use_redis – primarily for testing, this instance of one of the
redisorredisliteclasses in the typeredisent.common.RedisType. if provided, theRedisentHelper.get_connection()method will return it instead of building a new one with the providedredis_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.RedisEntryinstances 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_attemptThis is helpful for automatically returning
redisent.models.RedisEntryinstances and / or the opportunity to interact with the results via the twoCallableargumentsfirst_handlerandfinal_handler.If provided, the
first_handleris used first, prior to attempting to using thehandle_decode_attemptstatic method. Finally, if provided, thefinal_handlerwill 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.Redisorredis.StrictRedisinstance, based on the providedstrict_clientvalue.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 ofredis.Rediswill be returned
- __init__(redis_pool: redis.connection.ConnectionPool, use_redis: Optional[redis.client.Redis] = None) None[source]¶
Simple
ctormethod for buildingRedisentHelperinstance from a givenRedisPoolType- Parameters
redis_pool – Redis connection pool helper should use
use_redis – primarily for testing, this instance of one of the
redisorredisliteclasses in the typeredisent.common.RedisType. if provided, theRedisentHelper.get_connection()method will return it instead of building a new one with the providedredis_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
RedisPoolTypeinstance from the given Redis URIThis method uses
redis.connection.ConnectionPool.from_urlunder the hood to build the connection pool- Parameters
redis_uri – URI of Redis server (will be prefixed with
redis://if not present)
- 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_patternandredis_idare not provided, this method will useKEYS(*)to lookup all Redis keys.Otherwise, if
redis_idis provided, a lookup ofHKEYS(redis_id)will be done.Finally, if
use_patternis provided,KEYS(use_pattern)will be used- Parameters
use_pattern – if provided, use this value instead of
*withKEYSredis_id – if provided, use
HKEYS(redis_id)to lookup keys in the hash entryuse_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 optionalredis_namevalue, 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_identry- Parameters
redis_id – the Redis ID for entry
check_exists – if set, use the
RedisentHelper.exists()method to validate the entry exists or returnNone
- get(redis_id: str, redis_name: Optional[str] = None, throw_error: bool = True) Optional[Any][source]¶
Method for fetching Redis entry based on
redis_idand an optionalredis_namevalueIf
redis_nameis 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.RedisErrorexception will be raised if the entry cannot be fetched, otherwiseNonewill 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_idand optionalredis_namefor storing hashmap dataIf
redis_nameis alos provided, this operation will useHSETto create a hashmap. OtherwiseSETis used andvaluemust be an instance of one of the supportedredisent.common.RedisTypetypes.- 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
RedisTyperedis_name – if provided, store this entry as a hashmap using both
redis_idandredis_name
- Returns
bool indicating if there the value was being set for the first time (i.e.
Truemeans 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_idand optional hashmap nameredis_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. ifcheck_existsfails,Nonewill 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
RedisEntryinstances must define a unique-to-Redis value forredis_id. If the entry is going to be stored as a hash-map, the class must also define a value forredis_name.If the
redis_nameattribute 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}
- dump(include_internal_fields: bool = False) str[source]¶
Helper for dumping a textual representation of a particular
redisent.models.RedisEntryinstance
- 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
redisentonly (any marked with metadata attributeinternal_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_nameis 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_idorredis_name) are returned- Parameters
include_internal_fields – if set, include internal fields which are used by
redisentonly (any marked with metadata attributeinternal_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.RedisEntryinstance from the providedbytesvalueentry_bytesUnder the hood, this makes use of
pickle.loads()andredisent.models.RedisEntry.load_dictto actually attempt to build the entry while catching any related exceptions and propagating them asredisent.errors.RedisErrorexceptions.
- classmethod encode_entry(entry: redisent.models.RedisEntry, as_mapping: Optional[bool] = None) bytes[source]¶
Class method for encoding a given
redisent.models.RedisEntryinstance asbytesusing thepickle.dumps()method.- Parameters
entry – the
redisent.models.RedisEntryinstance to be encodedas_mapping – if provided,
entrywill be treated as a Redis hashmap entry. otherwise, the default behavior is to checkRedisEntry.redis_name
- store(helper: redisent.helpers.RedisentHelper) bool[source]¶
Blocking / synchronous method for storing this entry in Redis, using the provided
redisent.helpers.RedisentHelperinstance.This method will do the actual encoding using the
RedisEntry.encode_entry()method as well as make use of the provided helperredisent.helpers.RedisentHelper.wrapped_redis()(actually, this method makes use of theredisent.helpers.RedisentHelper.wrapped_redis()) context manager for storing the entry in Redis.- Parameters
helper – configured instance of
redisent.helpers.RedisentHelperto 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.RedisentHelperinstance.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 toRedisEntryinstances.- Parameters
helper – configured instance of
redisent.helpers.RedisentHelperto be used for fetching entriesredis_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
RedisEntryis 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.RedisentHelperinstance.This method will do the actual decoding using the
RedisEntry.decode_entry()method after fetching thebytesvalue from Redis using the helper-providedredisent.helpers.RedisentHelper.wrapped_redis()(actually, this method makes use of theredisent.helpers.RedisentHelper.wrapped_redis()) context manager for actually fetching from Redis.- Parameters
helper – configured instance of
redisent.helpers.RedisentHelperto be used for storing entryredis_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
RedisEntryis 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.RedisentHelperto be used to delete the entrycheck_exists – if set, check first that there is an existing Redis entry for this instance