From 5f412905ae7ddba44e94b5b35a1823b1fbf4b928 Mon Sep 17 00:00:00 2001 From: BO ZHANG Date: Wed, 20 Dec 2023 13:49:27 +0800 Subject: [PATCH] add retry --- csst_common/utils/__init__.py | 4 ++++ csst_common/utils/_retry.py | 29 +++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+) create mode 100644 csst_common/utils/_retry.py diff --git a/csst_common/utils/__init__.py b/csst_common/utils/__init__.py index 219871d..fc5b7f1 100644 --- a/csst_common/utils/__init__.py +++ b/csst_common/utils/__init__.py @@ -10,4 +10,8 @@ Modified-History: """ from ._module_docstr import ModuleHeader +from ._retry import retry from .tempfile import randfile + + + diff --git a/csst_common/utils/_retry.py b/csst_common/utils/_retry.py new file mode 100644 index 0000000..d11e4cc --- /dev/null +++ b/csst_common/utils/_retry.py @@ -0,0 +1,29 @@ +""" +Identifier: csst_common/utils/_retry.py +Name: _retry.py +Description: CSST utils +Author: Bo Zhang +Created: 2023-12-20 +Modified-History: + 2023-12-20, Bo Zhang, add retry +""" + + +def retry(func, n_try=3, *args, **kwargs): + # is DFS? + try: + assert func.__self__.__class__.__module__.startswith("csst_dfs_api"), func + is_dfs = True + except BaseException: + is_dfs = False + # start trials + for attempt in range(n_try): + print(f"Trial #{attempt}: call {func}") + try: + res = func(*args, **kwargs) + if is_dfs: + assert res["code"] == 0, res + return res + except BaseException as e: + print(f"Error occurs: {e.__repr__()}") + raise RuntimeError(f"All {n_try} attempts failed.") -- GitLab