本文整理汇总了Python中redis.exceptions.ConnectionError方法的典型用法代码示例。如果您正苦于以下问题:Python exceptions.ConnectionError方法的具体用法?Python exceptions.ConnectionError怎么用?Python exceptions.ConnectionError使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类redis.exceptions
的用法示例。
在下文中一共展示了exceptions.ConnectionError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _current_id
# 需要导入模块: from redis import exceptions [as 别名]
# 或者: from redis.exceptions import ConnectionError [as 别名]
def _current_id(self, value):
futures, num_masters_set = set(), 0
with concurrent.futures.ThreadPoolExecutor() as executor:
for master in self.masters:
future = executor.submit(
self._set_id_script,
keys=(self.key,),
args=(value,),
client=master,
)
futures.add(future)
for future in concurrent.futures.as_completed(futures):
with contextlib.suppress(TimeoutError, ConnectionError):
num_masters_set += future.result() == value
if num_masters_set < len(self.masters) // 2 + 1:
raise QuorumNotAchieved(self.masters, self.key)
示例2: _acquire_masters
# 需要导入模块: from redis import exceptions [as 别名]
# 或者: from redis.exceptions import ConnectionError [as 别名]
def _acquire_masters(self):
self._value = os.urandom(self.num_random_bytes)
self._extension_num = 0
futures, num_masters_acquired = set(), 0
with ContextTimer() as timer, \
concurrent.futures.ThreadPoolExecutor() as executor:
for master in self.masters:
futures.add(executor.submit(self._acquire_master, master))
for future in concurrent.futures.as_completed(futures):
with contextlib.suppress(TimeoutError, ConnectionError):
num_masters_acquired += future.result()
quorum = num_masters_acquired >= len(self.masters) // 2 + 1
elapsed = timer.elapsed() - self._drift()
validity_time = self.auto_release_time - elapsed
if quorum and max(validity_time, 0):
return True
else:
with contextlib.suppress(ReleaseUnlockedLock):
self.release()
return False
示例3: listManagement
# 需要导入模块: from redis import exceptions [as 别名]
# 或者: from redis.exceptions import ConnectionError [as 别名]
def listManagement(self, vendor=None, product=None):
try:
if product is None:
# no product selected yet, so same function as /browse can be used
if vendor:
vendor = urllib.parse.quote_plus(vendor).lower()
browseList = query.getBrowseList(vendor)
vendor = browseList["vendor"]
product = browseList["product"]
version = None
else:
# product selected, product versions required
version = query.getVersionsOfProduct(urllib.parse.quote_plus(product).lower())
return render_template('listmanagement.html', vendor=vendor, product=product, version=version)
except redisExceptions.ConnectionError:
return render_template('error.html',
status={'except':'redis-connection',
'info':{'host':Configuration.getRedisHost(),'port':Configuration.getRedisPort()}})
# /admin/listmanagement/add
示例4: test_send_result_to_redis
# 需要导入模块: from redis import exceptions [as 别名]
# 或者: from redis.exceptions import ConnectionError [as 别名]
def test_send_result_to_redis(self):
# test not connected
self.rest_service.redis_connected = False
self.rest_service.logger.warning = MagicMock()
self.rest_service._send_result_to_redis('stuff')
self.assertTrue(self.rest_service.logger.warning.called)
# test connected
self.rest_service.redis_connected = True
self.rest_service.redis_conn = MagicMock()
self.rest_service.redis_conn.set = MagicMock()
self.rest_service._send_result_to_redis({'uuid': 'abc'})
self.rest_service.redis_conn.set.assert_called_with('rest:poll:abc',
'{"uuid": "abc"}')
# throw error
self.rest_service._spawn_redis_connection_thread = MagicMock()
self.rest_service.redis_conn.set = MagicMock(side_effect=ConnectionError)
self.rest_service._send_result_to_redis({'uuid': 'abc'})
self.assertTrue(self.rest_service._spawn_redis_connection_thread.called)
示例5: test_report_self
# 需要导入模块: from redis import exceptions [as 别名]
# 或者: from redis.exceptions import ConnectionError [as 别名]
def test_report_self(self, h):
# test not connected
self.rest_service.redis_connected = False
self.rest_service.logger.warn = MagicMock()
self.rest_service._report_self()
self.assertTrue(self.rest_service.logger.warn.called)
# test connected
self.rest_service.my_uuid = 'abc999'
self.rest_service.get_time = MagicMock(return_value=5)
self.rest_service.redis_connected = True
self.rest_service.redis_conn = MagicMock()
self.rest_service.redis_conn.set = MagicMock()
self.rest_service._report_self()
self.rest_service.redis_conn.set.assert_called_with('stats:rest:self:host:abc999',
5)
# throw error
self.rest_service._spawn_redis_connection_thread = MagicMock()
self.rest_service.redis_conn.expire = MagicMock(side_effect=ConnectionError)
self.rest_service._report_self()
self.assertTrue(self.rest_service._spawn_redis_connection_thread.called)
示例6: _report_self
# 需要导入模块: from redis import exceptions [as 别名]
# 或者: from redis.exceptions import ConnectionError [as 别名]
def _report_self(self):
"""
Reports the crawler uuid to redis
"""
if self.redis_connected:
self.logger.debug("Reporting self to redis")
try:
key = "stats:rest:self:{m}:{u}".format(
m=socket.gethostname(),
u=self.my_uuid)
self.redis_conn.set(key, self.get_time())
self.redis_conn.expire(key, self.settings['HEARTBEAT_TIMEOUT'])
except ConnectionError:
self.logger.error("Lost connection to Redis")
self._spawn_redis_connection_thread()
else:
self.logger.warn("Cannot report self to redis, not connected")
示例7: setup
# 需要导入模块: from redis import exceptions [as 别名]
# 或者: from redis.exceptions import ConnectionError [as 别名]
def setup(self, settings):
'''
Setup redis and tldextract
'''
self.extract = tldextract.TLDExtract()
self.redis_conn = redis.Redis(host=settings['REDIS_HOST'],
port=settings['REDIS_PORT'],
db=settings.get('REDIS_DB'))
try:
self.redis_conn.info()
self.logger.debug("Connected to Redis in ActionHandler")
except ConnectionError:
self.logger.error("Failed to connect to Redis in ActionHandler")
# plugin is essential to functionality
sys.exit(1)
示例8: setup
# 需要导入模块: from redis import exceptions [as 别名]
# 或者: from redis.exceptions import ConnectionError [as 别名]
def setup(self, settings):
'''
Setup redis and tldextract
'''
self.extract = tldextract.TLDExtract()
self.redis_conn = redis.Redis(host=settings['REDIS_HOST'],
port=settings['REDIS_PORT'],
db=settings.get('REDIS_DB'))
try:
self.redis_conn.info()
self.logger.debug("Connected to Redis in ZookeeperHandler")
except ConnectionError:
self.logger.error("Failed to connect to Redis in ZookeeperHandler")
# plugin is essential to functionality
sys.exit(1)
示例9: setup
# 需要导入模块: from redis import exceptions [as 别名]
# 或者: from redis.exceptions import ConnectionError [as 别名]
def setup(self, settings):
'''
Setup redis and tldextract
'''
self.extract = tldextract.TLDExtract()
self.redis_conn = redis.Redis(host=settings['REDIS_HOST'],
port=settings['REDIS_PORT'],
db=settings.get('REDIS_DB'))
try:
self.redis_conn.info()
self.logger.debug("Connected to Redis in ScraperHandler")
except ConnectionError:
self.logger.error("Failed to connect to Redis in ScraperHandler")
# plugin is essential to functionality
sys.exit(1)
示例10: get_connection
# 需要导入模块: from redis import exceptions [as 别名]
# 或者: from redis.exceptions import ConnectionError [as 别名]
def get_connection(self, command_name, shard_hint=None):
host_id = shard_hint
if host_id is None:
raise RuntimeError('The routing pool requires the host id '
'as shard hint')
real_pool = self.cluster.get_pool_for_host(host_id)
# When we check something out from the real underlying pool it's
# very much possible that the connection is stale. This is why we
# check out up to 10 connections which are either not connected
# yet or verified alive.
for _ in xrange(10):
con = real_pool.get_connection(command_name)
if con._sock is None or not is_closed(con._sock):
con.__creating_pool = weakref(real_pool)
return con
raise ConnectionError('Failed to check out a valid connection '
'(host %s)' % host_id)
示例11: execute_command
# 需要导入模块: from redis import exceptions [as 别名]
# 或者: from redis.exceptions import ConnectionError [as 别名]
def execute_command(self, *args, **options):
pool = self.connection_pool
command_name = args[0]
command_args = args[1:]
router = self.connection_pool.cluster.get_router()
host_id = router.get_host_for_command(command_name, command_args)
connection = pool.get_connection(command_name, shard_hint=host_id)
try:
connection.send_command(*args)
return self.parse_response(connection, command_name, **options)
except (ConnectionError, TimeoutError) as e:
connection.disconnect()
if not connection.retry_on_timeout and isinstance(e, TimeoutError):
raise
connection.send_command(*args)
return self.parse_response(connection, command_name, **options)
finally:
pool.release(connection)
# Custom Public API
示例12: set
# 需要导入模块: from redis import exceptions [as 别名]
# 或者: from redis.exceptions import ConnectionError [as 别名]
def set(self, key, value, ttl):
"""
Set the value for a key. Dark writes to the backup in-memory store are always performed
to synchronize the state of the in-memory store with Redis, so that read failovers do not
sacrifice the consistency of the underlying data.
:param key: Raw key.
:param value: Associated value.
:param ttl: Time to live, in milliseconds.
"""
try:
return self.redis.set(key, value, px=ttl)
except (ConnectionError, TimeoutError):
pass
finally:
return self.memory.set(key, value, ttl)
示例13: discover_master
# 需要导入模块: from redis import exceptions [as 别名]
# 或者: from redis.exceptions import ConnectionError [as 别名]
def discover_master(self, service_name):
"""
Asks sentinel servers for the Redis master's address corresponding
to the service labeled ``service_name``.
Returns a pair (address, port) or raises MasterNotFoundError if no
master is found.
"""
for sentinel_no, sentinel in enumerate(self.sentinels):
try:
masters = sentinel.sentinel_masters()
except ConnectionError:
continue
state = masters.get(service_name)
if state and self.check_master_state(state, service_name):
# Put this sentinel at the top of the list
self.sentinels[0], self.sentinels[sentinel_no] = (
sentinel, self.sentinels[0])
return state['ip'], state['port']
raise MasterNotFoundError("No master found for %r" % (service_name,))
示例14: test_redis_event_manager_installed
# 需要导入模块: from redis import exceptions [as 别名]
# 或者: from redis.exceptions import ConnectionError [as 别名]
def test_redis_event_manager_installed():
"""Test that RedisEventManager is installed on the Flask app"""
class RedisConfig(TestingConfig):
REDIS_URL = "redis://localhost:6379/1"
CACHE_REDIS_URL = "redis://localhost:6379/1"
CACHE_TYPE = "redis"
try:
app = create_ctfd(config=RedisConfig)
except ConnectionError:
print("Failed to connect to redis. Skipping test.")
else:
with app.app_context():
assert isinstance(app.events_manager, RedisEventManager)
destroy_ctfd(app)
示例15: api_browse
# 需要导入模块: from redis import exceptions [as 别名]
# 或者: from redis.exceptions import ConnectionError [as 别名]
def api_browse(self, vendor=None):
if vendor:
vendor = urllib.parse.quote_plus(vendor).lower()
try:
browseList = query.getBrowseList(vendor)
except redisExceptions.ConnectionError:
raise(APIError("Server could not connect to the browsing repository", 503))
if isinstance(browseList, dict):
return browseList
else:
return {}
# /api/search/<vendor>/<path:product>