mirror of https://github.com/peter4431/rq.git
Patch the connection instances.
This patches the connection object (which is either a StrictRedis instance or a Redis instance), to have alternative class methods that behave exactly like their StrictRedis counterparts, no matter whether which type the object is. Only the ambiguous methods are patched. The exhaustive list: - _zadd (fixes argument order) - _lrem (fixes argument order) - _setex (fixes argument order) - _pipeline (always returns a StrictPipeline) - _ttl (fixes return value) - _pttl (fixes return value) This makes it possible to call the methods reliably without polluting the RQ code any further.main
parent
67880343f1
commit
54254f2271
@ -0,0 +1,44 @@
|
||||
from redis import Redis, StrictRedis
|
||||
from functools import partial
|
||||
|
||||
|
||||
def fix_return_type(func):
|
||||
# deliberately no functools.wraps() call here, since the function being
|
||||
# wrapped is a partial, which has no module
|
||||
def _inner(*args, **kwargs):
|
||||
value = func(*args, **kwargs)
|
||||
if value is None:
|
||||
value = -1
|
||||
return value
|
||||
return _inner
|
||||
|
||||
|
||||
def patch_connection(connection):
|
||||
if not isinstance(connection, StrictRedis):
|
||||
raise ValueError('A StrictRedis or Redis connection is required.')
|
||||
|
||||
# Don't patch already patches objects
|
||||
PATCHED_METHODS = ['_setex', '_lrem', '_zadd', '_pipeline', '_ttl']
|
||||
if all([hasattr(connection, attr) for attr in PATCHED_METHODS]):
|
||||
return connection
|
||||
|
||||
if isinstance(connection, Redis):
|
||||
connection._setex = partial(StrictRedis.setex, connection)
|
||||
connection._lrem = partial(StrictRedis.lrem, connection)
|
||||
connection._zadd = partial(StrictRedis.zadd, connection)
|
||||
connection._pipeline = partial(StrictRedis.pipeline, connection)
|
||||
connection._ttl = fix_return_type(partial(StrictRedis.ttl, connection))
|
||||
if hasattr(connection, 'pttl'):
|
||||
connection._pttl = fix_return_type(partial(StrictRedis.pttl, connection))
|
||||
elif isinstance(connection, StrictRedis):
|
||||
connection._setex = connection.setex
|
||||
connection._lrem = connection.lrem
|
||||
connection._zadd = connection.zadd
|
||||
connection._pipeline = connection.pipeline
|
||||
connection._ttl = connection.ttl
|
||||
if hasattr(connection, 'pttl'):
|
||||
connection._pttl = connection.pttl
|
||||
else:
|
||||
raise ValueError('Unanticipated connection type: {}. Please report this.'.format(type(connection)))
|
||||
|
||||
return connection
|
Loading…
Reference in New Issue