Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def _resolve_waiters(self, results, return_exceptions):
errors = []
for val, fut in zip(results, self._waiters):
if isinstance(val, RedisError):
fut.set_exception(val)
errors.append(val)
else:
fut.set_result(val)
if errors and not return_exceptions:
raise MultiExecError(errors)
Raises:
* TypeError if any of args can not be encoded as bytes.
* ReplyError on redis '-ERR' resonses.
* ProtocolError when response can not be decoded meaning connection
is broken.
"""
if self._reader is None or self._reader.at_eof():
raise ConnectionClosedError("Connection closed or corrupted")
if command is None:
raise TypeError("command must not be None")
if None in set(args):
raise TypeError("args must not contain None")
command = command.upper().strip()
is_pubsub = command in _PUBSUB_COMMANDS
if self._in_pubsub and not is_pubsub:
raise RedisError("Connection in SUBSCRIBE mode")
elif is_pubsub:
logger.warning("Deprecated. Use `execute_pubsub` method directly")
return self.execute_pubsub(command, *args)
if command in ('SELECT', b'SELECT'):
cb = partial(self._set_db, args=args)
elif command in ('MULTI', b'MULTI'):
cb = self._start_transaction
elif command in ('EXEC', b'EXEC'):
cb = partial(self._end_transaction, discard=False)
elif command in ('DISCARD', b'DISCARD'):
cb = partial(self._end_transaction, discard=True)
else:
cb = None
if encoding is _NOTSET:
encoding = self._encoding
pool = self._slaves[service]
with async_timeout(timeout), \
contextlib.ExitStack() as stack:
conn = await pool._create_new_connection(address)
stack.callback(conn.close)
await self._verify_service_role(conn, 'slave')
stack.pop_all()
return conn
except asyncio.CancelledError:
raise
except asyncio.TimeoutError:
continue
except DiscoverError:
await asyncio.sleep(idle_timeout)
continue
except RedisError as err:
raise SlaveReplyError("Service {} error".format(service), err)
except Exception:
await asyncio.sleep(idle_timeout)
continue
raise SlaveNotFoundError("No slave found for {}".format(service))
addr, **self._conn_kwargs)
self._conn = conn
else:
service = self._sentinel_service
slaves = yield from service.get_slaves()
num = service.num_slaves()
for idx in range(num):
slave = slaves[idx]
try:
conn = yield from create_connection(
slave, **self._conn_kwargs)
self._conn = conn
return self._conn
except SlaveNotFoundError:
raise
except RedisError:
pass
addr = yield from service.get_master_address()
try:
conn = yield from create_connection(
addr, **self._conn_kwargs)
self._conn = conn
return self._conn
except RedisError:
raise SlaveNotFoundError
return self._conn
class PipelineError(ReplyError):
"""Raised if command within pipeline raised error."""
def __init__(self, errors):
super().__init__('{} errors:'.format(self.__class__.__name__), errors)
class MultiExecError(PipelineError):
"""Raised if command within MULTI/EXEC block caused error."""
class WatchVariableError(MultiExecError):
"""Raised if watched variable changed (EXEC returns None)."""
class ChannelClosedError(RedisError):
"""Raised when Pub/Sub channel is unsubscribed and messages queue is empty.
"""
class ConnectionClosedError(RedisError):
"""Raised if connection to server was closed.
Has additional `reason` attribute holding CloseReason enum value or None.
"""
def __init__(self, message, *, reason=None):
super().__init__(message)
self.reason = reason
class PoolClosedError(RedisError):
"""Raised if pool is closed."""
"""
lock_timeout_ms = int(lock_timeout * 1000)
try:
with await self.connect() as redis:
await redis.eval(
self.set_lock_script,
keys=[resource],
args=[lock_identifier, lock_timeout_ms]
)
except aioredis.errors.ReplyError as exc: # script fault
self.log.debug('Can not set lock "%s" on %s',
resource, repr(self))
raise LockError('Can not set lock') from exc
except (aioredis.errors.RedisError, OSError) as exc:
self.log.error('Can not set lock "%s" on %s: %s',
resource, repr(self), repr(exc))
raise LockError('Can not set lock') from exc
except asyncio.CancelledError:
self.log.debug('Lock "%s" is cancelled on %s',
resource, repr(self))
raise
except Exception as exc:
self.log.exception('Can not set lock "%s" on %s',
resource, repr(self))
raise
else:
self.log.debug('Lock "%s" is set on %s', resource, repr(self))
'ReplyError',
'PipelineError',
'MultiExecError',
'WatchVariableError',
'ChannelClosedError',
'ConnectionClosedError',
'PoolClosedError',
'CloseReason',
]
class RedisError(Exception):
"""Base exception class for aioredis exceptions."""
class ProtocolError(RedisError):
"""Raised when protocol error occurs."""
class ReplyError(RedisError):
"""Raised for redis error replies (-ERR)."""
class PipelineError(ReplyError):
"""Raised if command within pipeline raised error."""
def __init__(self, errors):
super().__init__('{} errors:'.format(self.__class__.__name__), errors)
class MultiExecError(PipelineError):
"""Raised if command within MULTI/EXEC block caused error."""