From c99948eb95784029105ba2c51c94726e574afbc7 Mon Sep 17 00:00:00 2001 From: Siarhei Siniak Date: Sat, 6 Jul 2024 22:05:33 +0300 Subject: [PATCH] [~] Refactor --- python/tasks/tiktok/utils.py | 45 ++++++++++++++++++++++++++++++------ 1 file changed, 38 insertions(+), 7 deletions(-) diff --git a/python/tasks/tiktok/utils.py b/python/tasks/tiktok/utils.py index 612e7fd..8f71205 100644 --- a/python/tasks/tiktok/utils.py +++ b/python/tasks/tiktok/utils.py @@ -6,23 +6,54 @@ import kombu.utils.json from typing import ( Any, Optional, + Callable, ) -def shared_task(*args: Any, **kwargs: Any) -> Any: - return celery.shared_task( - *args, - base=Task, - **kwargs - ) +def shared_task(func: Optional[Callable[Any, Any]]=None, **kwargs: Any) -> Any: + #@celery.shared_task( + # base=Task, + # **kwargs, + #) + #def decorator2(*args, **kwargs): + # res = func(*args, **kwargs) + # + # if inspect.isawaitable(res): + # return asyncio.run(res) + # else: + # return res + # + #def decorator(func2: Callable[Any, Any]): + # nonlocal func + # + # if func is None: + # func = func2 + # + # return decorator2 + # + #if func is None: + # return decorator + #else: + # return decorator2 + return celery.shared_task(base=Task, **kwargs) + +def is_async() -> bool: + try: + asyncio.get_running_loop() + return True + except RuntimeError: + return False class Task(celery.app.task.Task): def __call__(self, *args, **kwargs) -> Any: res = super().__call__(*args, **kwargs) - if inspect.isawaitable(res): + if inspect.isawaitable(res) and not is_async(): return asyncio.run(res) else: return res + #def apply(self, *args, **kwargs): + # return self.__call__(*args, **kwargs) + @classmethod def _loads( cls,