Skip to content

Commit 04a0bdb

Browse files
committed
tidy up
1 parent cf16c4c commit 04a0bdb

File tree

2 files changed

+21
-16
lines changed

2 files changed

+21
-16
lines changed

codeforlife/settings/third_party.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,13 @@
77

88
import typing as t
99

10-
from ..tasks import CeleryBeat
1110
from .custom import REDIS_URL, SERVICE_SITE_URL
1211
from .django import ENV
1312

13+
if t.TYPE_CHECKING:
14+
from ..tasks import CeleryBeat
15+
16+
1417
# CORS
1518
# https://pypi.org/project/django-cors-headers/
1619

@@ -37,4 +40,4 @@
3740

3841
CELERY_BROKER_URL = REDIS_URL
3942
CELERY_TASK_TIME_LIMIT = 60 * 30
40-
CELERY_BEAT_SCHEDULE: t.Dict[str, CeleryBeat] = {}
43+
CELERY_BEAT_SCHEDULE: t.Dict[str, "CeleryBeat"] = {}

codeforlife/tasks.py

Lines changed: 16 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -27,10 +27,21 @@ class CeleryBeat(t.TypedDict):
2727
args: t.NotRequired[Args]
2828
kwargs: t.NotRequired[KwArgs]
2929

30-
def __init__(self, **kwargs): # type: ignore[misc]
31-
kwargs["task"] = f"{settings.SERVICE_NAME}.{kwargs['task']}"
3230

33-
super().__init__(**kwargs)
31+
def namespace_task(task: t.Union[str, t.Callable]):
32+
"""Namespace a task by the service it's in.
33+
34+
Args:
35+
task: The name of the task.
36+
37+
Returns:
38+
The name of the task in the format: "{SERVICE_NAME}.{TASK_NAME}".
39+
"""
40+
41+
if callable(task):
42+
task = f"{task.__module__}.{task.__name__}"
43+
44+
return f"{settings.SERVICE_NAME}.{task}"
3445

3546

3647
def shared_task(*args, **kwargs):
@@ -39,21 +50,12 @@ def shared_task(*args, **kwargs):
3950
tasks to a specific service.
4051
"""
4152

42-
def get_name(func: t.Callable):
43-
return ".".join(
44-
[
45-
settings.SERVICE_NAME,
46-
func.__module__,
47-
func.__name__,
48-
]
49-
)
50-
5153
if len(args) == 1 and callable(args[0]):
5254
func = args[0]
53-
return _shared_task(name=get_name(func))(func)
55+
return _shared_task(name=namespace_task(func))(func)
5456

5557
def wrapper(func: t.Callable):
5658
kwargs.pop("name", None)
57-
return _shared_task(name=get_name(func), *args, **kwargs)(func)
59+
return _shared_task(name=namespace_task(func), *args, **kwargs)(func)
5860

5961
return wrapper

0 commit comments

Comments
 (0)