Skip to content

Commit

Permalink
style(Retry): 修改 Type Hint 以及部分变量名
Browse files Browse the repository at this point in the history
  • Loading branch information
Akimio521 committed Dec 4, 2024
1 parent ac6becb commit d5bf52a
Showing 1 changed file with 15 additions and 12 deletions.
27 changes: 15 additions & 12 deletions app/utils/retry.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
from asyncio import sleep as async_sleep
from typing import TypeVar, Callable
from typing import TypeVar, Callable, Any
from time import sleep
from functools import wraps
from collections.abc import Coroutine

from app.core.log import logger
from app.utils.singleton import Singleton
Expand Down Expand Up @@ -41,14 +42,14 @@ def sync_retry(
:param ret: 默认返回
"""

def deco_retry(f: Callable[..., T1]) -> Callable[..., T1 | T2]:
def inner(func: Callable[..., T1]) -> Callable[..., T1 | T2]:

@wraps
def f_retry(*args, **kwargs) -> T1 | T2:
def warpper(*args, **kwargs) -> T1 | T2:
remaining_retries = tries
while remaining_retries > 0:
try:
return f(*args, **kwargs)
return func(*args, **kwargs)
except exception as e:
remaining_retries -= 1
if remaining_retries >= 0:
Expand All @@ -59,9 +60,9 @@ def f_retry(*args, **kwargs) -> T1 | T2:
logger.error(cls.ERROR_MSG.format(e))
return ret

return f_retry
return warpper

return deco_retry
return inner

@classmethod
def async_retry(
Expand All @@ -71,7 +72,7 @@ def async_retry(
delay: int = DELAY,
backoff: int = BACKOFF,
ret: T1 = None,
) -> Callable[..., Callable[..., T1 | T2]]:
) -> Callable[..., Callable[..., Coroutine[Any, Any, T1 | T2]]]:
"""
异步重试装饰器
Expand All @@ -82,14 +83,16 @@ def async_retry(
:param ret: 默认返回
"""

def deco_retry(f: Callable[..., T1]) -> Callable[..., T1 | T2]:
def inner(
func: Callable[..., T1]
) -> Callable[..., Coroutine[Any, Any, T1 | T2]]:

@wraps
async def f_retry(*args, **kwargs) -> T1 | T2:
async def warpper(*args, **kwargs) -> T1 | T2:
remaining_retries = tries
while remaining_retries > 0:
try:
return await f(*args, **kwargs)
return await func(*args, **kwargs)
except exception as e:
remaining_retries -= 1
if remaining_retries >= 0:
Expand All @@ -100,6 +103,6 @@ async def f_retry(*args, **kwargs) -> T1 | T2:
logger.error(cls.ERROR_MSG.format(e))
return ret

return f_retry
return warpper

return deco_retry
return inner

0 comments on commit d5bf52a

Please sign in to comment.