本文整理汇总了Python中retry.retry方法的典型用法代码示例。如果您正苦于以下问题:Python retry.retry方法的具体用法?Python retry.retry怎么用?Python retry.retry使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类retry
的用法示例。
在下文中一共展示了retry.retry方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: dump_hierarchy
# 需要导入模块: import retry [as 别名]
# 或者: from retry import retry [as 别名]
def dump_hierarchy(self, compressed=False, pretty=False) -> str:
"""
Args:
shell (bool): use "adb shell uiautomator dump" to get hierarchy
pretty (bool): format xml
Same as
content = self.jsonrpc.dumpWindowHierarchy(compressed, None)
But through GET /dump/hierarchy will be more robust
when dumpHierarchy fails, the atx-agent will restart uiautomator again, then retry
v-1.3.4 change back to jsonrpc.dumpWindowHierarchy
"""
content = self.jsonrpc.dumpWindowHierarchy(compressed, None)
if content == "":
raise RetryError("dump hierarchy is empty")
if pretty and "\n " not in content:
xml_text = xml.dom.minidom.parseString(content.encode("utf-8"))
content = xml_text.decode('utf-8').toprettyxml(indent=' ')
return content
示例2: test_unsuccessful_thread
# 需要导入模块: import retry [as 别名]
# 或者: from retry import retry [as 别名]
def test_unsuccessful_thread():
"""Unsuccessful with function as thread, timed out"""
retryed = []
def foo(retryed):
@retry.retry(timeout=1, success=lambda x: False)
def bar(retryed):
sleep(0.2)
retryed.append(0)
with pytest.raises(retry.MaximumTimeoutExceeded):
bar(retryed)
t = Thread(target=foo, args=[retryed])
t.start()
t.join()
assert 3 <= len(retryed) <= 5
示例3: handle_error
# 需要导入模块: import retry [as 别名]
# 或者: from retry import retry [as 别名]
def handle_error(tries=20, delay=0.01):
def decorate(func):
@wraps(func)
@retry(tries=tries, delay=delay)
def wrapper(*args, **kwargs):
try:
func(*args, **kwargs)
except Exception as error:
print(f'Raise an error: {error}')
print(f'Start to retry!!!!!')
raise Exception
return wrapper
return decorate
示例4: request
# 需要导入模块: import retry [as 别名]
# 或者: from retry import retry [as 别名]
def request(self, method, url, **kwargs):
retry = kwargs.pop("retry", True)
try:
url = self.__client.path2url(
url) # may raise adbutils.AdbError when device offline
return super().request(method, url, **kwargs)
except (requests.ConnectionError, requests.ReadTimeout,
adbutils.AdbError) as e:
if not retry:
raise
# if atx-agent is already running, just raise error
if isinstance(e, requests.RequestException) and \
self.__client._is_agent_alive():
raise
if not self.__client._serial:
raise EnvironmentError(
"http-request to atx-agent error, can only recover from USB")
logger.warning("atx-agent has something wrong, auto recovering")
# ReadTimeout: sometime means atx-agent is running but not responsing
# one reason is futex_wait_queue: https://stackoverflow.com/questions/9801256/app-hangs-on-futex-wait-queue-me-every-a-couple-of-minutes
# fix atx-agent and request again
self.__client._prepare_atx_agent()
url = self.__client.path2url(url)
return super().request(method, url, **kwargs)
示例5: _invalid_session_err_callback
# 需要导入模块: import retry [as 别名]
# 或者: from retry import retry [as 别名]
def _invalid_session_err_callback(self, hc: HTTPClient, err):
if self.__is_app and self.__session_id: # ignore when app is crashed
return False
if err.status == Status.INVALID_SESSION_ID:
# update session id and retry
# print("Invalid session id,: update session url", self._id)
self.__session_id = None
hc.address = self.http.address + "/session/" + self.id
return True
return False
示例6: __init__
# 需要导入模块: import retry [as 别名]
# 或者: from retry import retry [as 别名]
def __init__(self):
super(TimeoutRequestsSession, self).__init__()
# refs: https://stackoverflow.com/questions/33895739/python-requests-cant-load-any-url-remote-end-closed-connection-without-respo
# refs: https://stackoverflow.com/questions/15431044/can-i-set-max-retries-for-requests-request
# Is retry necessary, maybe not, so I closed it at 2020/05/29
# retries = Retry(total=3, connect=3, backoff_factor=0.5)
# adapter = requests.adapters.HTTPAdapter(max_retries=retries)
# self.mount("http://", adapter)
# self.mount("https://", adapter)
示例7: _is_alive
# 需要导入模块: import retry [as 别名]
# 或者: from retry import retry [as 别名]
def _is_alive(self):
try:
r = self.http.post("/jsonrpc/0", timeout=2, retry=False, data=json.dumps({
"jsonrpc": "2.0",
"id": 1,
"method": "deviceInfo",
}))
if r.status_code != 200:
return False
if r.json().get("error"):
return False
return True
except (requests.ReadTimeout, EnvironmentError):
return False
示例8: get_original_variable
# 需要导入模块: import retry [as 别名]
# 或者: from retry import retry [as 别名]
def get_original_variable(self, samples, radius, variable):
try:
# if we have already calculated the grid, return it
var = self.grids[(samples, radius)]['original'][variable]
return var
except KeyError as e:
# otherwise, raise. The function will retry which leads to
# the above (returning) codepath running
self.make_basic_grids(samples, radius)
raise e
示例9: get_transformed_variable
# 需要导入模块: import retry [as 别名]
# 或者: from retry import retry [as 别名]
def get_transformed_variable(self, samples, radius, transformation):
try:
# if we have already calculated the grid, return it
var = self.grids[(samples, radius)]['transformed'][transformation]
return var
except KeyError as e:
# otherwise, raise. The function will retry which leads to
# the above (returning) codepath running
self.make_transformation(samples, radius, transformation)
raise e
示例10: test_success_criteria
# 需要导入模块: import retry [as 别名]
# 或者: from retry import retry [as 别名]
def test_success_criteria():
"""Success criteria successfully raises MaximumRetriesExceeded"""
foo_with_success = retry.retry(success=lambda x: x > 0)(foo)
with pytest.raises(retry.MaximumRetriesExceeded):
foo_with_success(0)
示例11: test_exception_criteria
# 需要导入模块: import retry [as 别名]
# 或者: from retry import retry [as 别名]
def test_exception_criteria():
"""Exceptions specified are raised on MaximumRetriesExceeded"""
foo_with_exception = retry.retry(exceptions=(ArithmeticError,))(foo)
with pytest.raises(ArithmeticError) as exc_info:
foo_with_exception(-1)
assert exception_message in str(exc_info.value)
示例12: test_execution
# 需要导入模块: import retry [as 别名]
# 或者: from retry import retry [as 别名]
def test_execution():
"""Expected execution of a successful runstill works"""
foo_with_both = retry.retry(
exceptions=(ArithmeticError,), success=lambda x: x > 0)(foo)
assert foo_with_both(1) == 1
示例13: test_interval
# 需要导入模块: import retry [as 别名]
# 或者: from retry import retry [as 别名]
def test_interval():
"""Interval expected is the interval to complete an action"""
def _success_interval(in_dict):
in_dict['num'] += 1
return in_dict['num']
baz_with_interval = retry.retry(
success=lambda x: x > 5, interval=1)(_success_interval)
start = datetime.now()
baz_with_interval({'num': 0})
elapsed = datetime.now() - start
assert elapsed.seconds >= 5
示例14: test_invalid_parameters
# 需要导入模块: import retry [as 别名]
# 或者: from retry import retry [as 别名]
def test_invalid_parameters():
"""The exceptions and success parameter can not both be None"""
with pytest.raises(TypeError):
retry.retry(exceptions=None, success=None)(foo)
示例15: test_successful_timeout
# 需要导入模块: import retry [as 别名]
# 或者: from retry import retry [as 别名]
def test_successful_timeout():
"""Success with a timeout still works"""
def _success_timeout(in_dict):
in_dict['num'] += 1
return in_dict['num']
try:
_test_func = retry.retry(
success=lambda x: x == 5, timeout=10, interval=1)(
_success_timeout)
_test_func({'num': 0})
except retry.MaximumTimeoutExceeded:
pytest.fail('Expected the timeout not to be exceeded')