本文整理汇总了Python中tenacity.wait_fixed方法的典型用法代码示例。如果您正苦于以下问题:Python tenacity.wait_fixed方法的具体用法?Python tenacity.wait_fixed怎么用?Python tenacity.wait_fixed使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tenacity
的用法示例。
在下文中一共展示了tenacity.wait_fixed方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _fetch
# 需要导入模块: import tenacity [as 别名]
# 或者: from tenacity import wait_fixed [as 别名]
def _fetch(self, url, verb='get', **kwargs):
"""return response or None in case of failure, try twice"""
@retry(stop=stop_after_attempt(2), wait=wait_fixed(2))
def _inner_fetch(verb='get'):
headers = {
'Authorization': 'apiToken %s' % C.DEFAULT_SHIPPABLE_TOKEN
}
logging.info(u'%s %s' % (verb, url))
http_method = getattr(requests, verb)
resp = http_method(url, headers=headers, **kwargs)
logging.info(u'shippable status code: %s' % resp.status_code)
logging.info(u'shippable reason: %s' % resp.reason)
if resp.status_code not in [200, 302, 400]:
logging.error(u'RC: %s', resp.status_code)
raise TryAgain
return resp
try:
logging.debug(u'%s' % url)
return _inner_fetch(verb=verb)
except RetryError as e:
logging.error(e)
示例2: test_retry_child_class_with_override_backward_compat
# 需要导入模块: import tenacity [as 别名]
# 或者: from tenacity import wait_fixed [as 别名]
def test_retry_child_class_with_override_backward_compat(self):
class MyStop(tenacity.stop_after_attempt):
def __init__(self):
super(MyStop, self).__init__(1)
def __call__(self, attempt_number, seconds_since_start):
return super(MyStop, self).__call__(
attempt_number, seconds_since_start)
retrying = Retrying(wait=tenacity.wait_fixed(0.01),
stop=MyStop())
def failing():
raise NotImplementedError()
with pytest.raises(RetryError):
retrying.call(failing)
示例3: test_wait_chain_multiple_invocations
# 需要导入模块: import tenacity [as 别名]
# 或者: from tenacity import wait_fixed [as 别名]
def test_wait_chain_multiple_invocations(self):
sleep_intervals = []
r = Retrying(
sleep=sleep_intervals.append,
wait=tenacity.wait_chain(*[
tenacity.wait_fixed(i + 1) for i in six.moves.range(3)
]),
stop=tenacity.stop_after_attempt(5),
retry=tenacity.retry_if_result(lambda x: x == 1),
)
@r.wraps
def always_return_1():
return 1
self.assertRaises(tenacity.RetryError, always_return_1)
self.assertEqual(sleep_intervals, [1.0, 2.0, 3.0, 3.0])
sleep_intervals[:] = []
# Clear and restart retrying.
self.assertRaises(tenacity.RetryError, always_return_1)
self.assertEqual(sleep_intervals, [1.0, 2.0, 3.0, 3.0])
sleep_intervals[:] = []
示例4: test_before_attempts
# 需要导入模块: import tenacity [as 别名]
# 或者: from tenacity import wait_fixed [as 别名]
def test_before_attempts(self):
TestBeforeAfterAttempts._attempt_number = 0
def _before(retry_state):
TestBeforeAfterAttempts._attempt_number = \
retry_state.attempt_number
@retry(wait=tenacity.wait_fixed(1),
stop=tenacity.stop_after_attempt(1),
before=_before)
def _test_before():
pass
_test_before()
self.assertTrue(TestBeforeAfterAttempts._attempt_number == 1)
示例5: test_after_attempts
# 需要导入模块: import tenacity [as 别名]
# 或者: from tenacity import wait_fixed [as 别名]
def test_after_attempts(self):
TestBeforeAfterAttempts._attempt_number = 0
def _after(retry_state):
TestBeforeAfterAttempts._attempt_number = \
retry_state.attempt_number
@retry(wait=tenacity.wait_fixed(0.1),
stop=tenacity.stop_after_attempt(3),
after=_after)
def _test_after():
if TestBeforeAfterAttempts._attempt_number < 2:
raise Exception("testing after_attempts handler")
else:
pass
_test_after()
self.assertTrue(TestBeforeAfterAttempts._attempt_number == 2)
示例6: test_before_sleep_backward_compat
# 需要导入模块: import tenacity [as 别名]
# 或者: from tenacity import wait_fixed [as 别名]
def test_before_sleep_backward_compat(self):
def _before_sleep(retry_obj, sleep, last_result):
self.assertGreater(sleep, 0)
_before_sleep.attempt_number = \
retry_obj.statistics['attempt_number']
_before_sleep.attempt_number = 0
@retry(wait=tenacity.wait_fixed(0.01),
stop=tenacity.stop_after_attempt(3),
before_sleep=_before_sleep)
def _test_before_sleep():
if _before_sleep.attempt_number < 2:
raise Exception("testing before_sleep_attempts handler")
with reports_deprecation_warning():
_test_before_sleep()
self.assertEqual(_before_sleep.attempt_number, 2)
示例7: test_before_sleep_log_returns
# 需要导入模块: import tenacity [as 别名]
# 或者: from tenacity import wait_fixed [as 别名]
def test_before_sleep_log_returns(self, exc_info=False):
thing = NoneReturnUntilAfterCount(2)
logger = logging.getLogger(self.id())
logger.propagate = False
logger.setLevel(logging.INFO)
handler = CapturingHandler()
logger.addHandler(handler)
try:
_before_sleep = tenacity.before_sleep_log(logger,
logging.INFO,
exc_info=exc_info)
_retry = tenacity.retry_if_result(lambda result: result is None)
retrying = Retrying(wait=tenacity.wait_fixed(0.01),
stop=tenacity.stop_after_attempt(3),
retry=_retry, before_sleep=_before_sleep)
retrying.call(thing.go)
finally:
logger.removeHandler(handler)
etalon_re = r'^Retrying .* in 0\.01 seconds as it returned None\.$'
self.assertEqual(len(handler.records), 2)
fmt = logging.Formatter().format
self.assertRegexpMatches(fmt(handler.records[0]), etalon_re)
self.assertRegexpMatches(fmt(handler.records[1]), etalon_re)
示例8: test_reraise_from_retry_error
# 需要导入模块: import tenacity [as 别名]
# 或者: from tenacity import wait_fixed [as 别名]
def test_reraise_from_retry_error(self):
calls = []
@retry(wait=tenacity.wait_fixed(0.1),
stop=tenacity.stop_after_attempt(2))
def _raise_key_error():
calls.append('x')
raise KeyError("Bad key")
def _reraised_key_error():
try:
_raise_key_error()
except tenacity.RetryError as retry_err:
retry_err.reraise()
self.assertRaises(KeyError, _reraised_key_error)
self.assertEqual(2, len(calls))
示例9: test_reraise_timeout_from_retry_error
# 需要导入模块: import tenacity [as 别名]
# 或者: from tenacity import wait_fixed [as 别名]
def test_reraise_timeout_from_retry_error(self):
calls = []
@retry(wait=tenacity.wait_fixed(0.1),
stop=tenacity.stop_after_attempt(2),
retry=lambda retry_state: True)
def _mock_fn():
calls.append('x')
def _reraised_mock_fn():
try:
_mock_fn()
except tenacity.RetryError as retry_err:
retry_err.reraise()
self.assertRaises(tenacity.RetryError, _reraised_mock_fn)
self.assertEqual(2, len(calls))
示例10: _do_it_with_persistence
# 需要导入模块: import tenacity [as 别名]
# 或者: from tenacity import wait_fixed [as 别名]
def _do_it_with_persistence(func, args, config):
"""Exec func with retries based on provided cli flags
:param: func: function to attempt to execute
:param: args: argparser generated cli arguments
:param: config: configparser object of vaultlocker config
"""
@tenacity.retry(
wait=tenacity.wait_fixed(1),
reraise=True,
stop=(
tenacity.stop_after_delay(args.retry) if args.retry > 0
else tenacity.stop_after_attempt(1)
),
retry=(
tenacity.retry_if_exception(hvac.exceptions.VaultNotInitialized) |
tenacity.retry_if_exception(hvac.exceptions.VaultDown)
)
)
def _do_it():
client = _vault_client(config)
func(args, client, config)
_do_it()
示例11: get_connection_from_config
# 需要导入模块: import tenacity [as 别名]
# 或者: from tenacity import wait_fixed [as 别名]
def get_connection_from_config(conf):
retries = conf.database.max_retries
url = conf.database.connection
connection_scheme = urlparse.urlparse(url).scheme
LOG.debug('looking for %(name)r driver in %(namespace)r',
{'name': connection_scheme, 'namespace': _NAMESPACE})
mgr = driver.DriverManager(_NAMESPACE, connection_scheme)
@tenacity.retry(
wait=tenacity.wait_fixed(conf.database.retry_interval),
stop=tenacity.stop_after_attempt(retries if retries >= 0 else 5),
reraise=True)
def _get_connection():
"""Return an open connection to the database."""
return mgr.driver(conf, url)
return _get_connection()
示例12: etcd
# 需要导入模块: import tenacity [as 别名]
# 或者: from tenacity import wait_fixed [as 别名]
def etcd(self):
endpoint = os.environ.get('PYTHON_ETCD_HTTP_URL')
timeout = 5
if endpoint:
url = urlparse(endpoint)
with etcd3.client(host=url.hostname,
port=url.port,
timeout=timeout) as client:
yield client
else:
with etcd3.client() as client:
yield client
@retry(wait=wait_fixed(2), stop=stop_after_attempt(3))
def delete_keys_definitely():
# clean up after fixture goes out of scope
etcdctl('del', '--prefix', '/')
out = etcdctl('get', '--prefix', '/')
assert 'kvs' not in out
delete_keys_definitely()
示例13: create_file
# 需要导入模块: import tenacity [as 别名]
# 或者: from tenacity import wait_fixed [as 别名]
def create_file(filename, after_delay=5):
time.sleep(after_delay)
with open(filename, 'w') as f:
f.write('A file creation test')
#@tenacity.retry(wait=tenacity.wait_fixed(2))
开发者ID:PacktPublishing,项目名称:Mastering-Python-Design-Patterns-Second-Edition,代码行数:9,代码来源:retry_write_file_tenacity_module.py
示例14: _get_connection
# 需要导入模块: import tenacity [as 别名]
# 或者: from tenacity import wait_fixed [as 别名]
def _get_connection(self):
"""Context manager providing a netmiko SSH connection object.
This function hides the complexities of gracefully handling retrying
failed connection attempts.
"""
retry_exc_types = (paramiko.SSHException, EOFError)
# Use tenacity to handle retrying.
@tenacity.retry(
# Log a message after each failed attempt.
after=tenacity.after_log(LOG, logging.DEBUG),
# Reraise exceptions if our final attempt fails.
reraise=True,
# Retry on SSH connection errors.
retry=tenacity.retry_if_exception_type(retry_exc_types),
# Stop after the configured timeout.
stop=tenacity.stop_after_delay(
int(self.ngs_config['ngs_ssh_connect_timeout'])),
# Wait for the configured interval between attempts.
wait=tenacity.wait_fixed(
int(self.ngs_config['ngs_ssh_connect_interval'])),
)
def _create_connection():
return netmiko.ConnectHandler(**self.config)
# First, create a connection.
try:
net_connect = _create_connection()
except tenacity.RetryError as e:
LOG.error("Reached maximum SSH connection attempts, not retrying")
raise exc.GenericSwitchNetmikoConnectError(
config=device_utils.sanitise_config(self.config), error=e)
except Exception as e:
LOG.error("Unexpected exception during SSH connection")
raise exc.GenericSwitchNetmikoConnectError(
config=device_utils.sanitise_config(self.config), error=e)
# Now yield the connection to the caller.
with net_connect:
yield net_connect
示例15: get_connection_from_config
# 需要导入模块: import tenacity [as 别名]
# 或者: from tenacity import wait_fixed [as 别名]
def get_connection_from_config():
retries = CONF.database.max_retries
url = CONF.database.connection
try:
# TOTO(iafek): check why this call randomly fails
connection_scheme = urlparse.urlparse(url).scheme
LOG.debug('looking for %(name)r driver in %(namespace)r',
{'name': connection_scheme, 'namespace': _NAMESPACE})
mgr = driver.DriverManager(_NAMESPACE, connection_scheme)
except Exception:
LOG.exception('Failed to get scheme %s.' % url)
return None
@tenacity.retry(
wait=tenacity.wait_fixed(CONF.database.retry_interval),
stop=tenacity.stop_after_attempt(retries),
after=tenacity.after_log(LOG, log.WARN),
reraise=True)
def _get_connection():
"""Return an open connection to the database."""
conn = mgr.driver(url)
session = conn._engine_facade.get_session()
session.execute('SELECT 1;')
return conn
return _get_connection()