diff --git a/django_celery_results/backends/database.py b/django_celery_results/backends/database.py index a4e364a6..29c08462 100644 --- a/django_celery_results/backends/database.py +++ b/django_celery_results/backends/database.py @@ -7,6 +7,7 @@ from celery.result import GroupResult, allow_join_result, result_from_tuple from celery.utils.log import get_logger from celery.utils.serialization import b64decode, b64encode +from django.conf import settings from django.db import connection, router, transaction from django.db.models.functions import Now from django.db.utils import InterfaceError @@ -93,13 +94,31 @@ def _get_extended_properties(self, request, traceback): 'periodic_task_name': periodic_task_name, 'task_args': task_args, 'task_kwargs': task_kwargs, - 'task_name': getattr(request, 'task', None), + 'task_name': self._get_task_name(request), 'traceback': traceback, 'worker': getattr(request, 'hostname', None), }) return extended_props + def _get_task_name(self, request): + """ + Get the task name from the request, optionally using the shadow name. + + If `DJANGO_CELERY_RESULTS_USE_SHADOW_NAME` is enabled and a shadow task + name is available, return the shadow task name; otherwise, return the + regular task name. + """ + use_shadow_name = ( + getattr(settings, "DJANGO_CELERY_RESULTS_USE_SHADOW_NAME", False) + is True + ) + task_name = getattr(request, "task", None) + if not use_shadow_name: + return task_name + shadow_task_name = getattr(request, "shadow", None) + return shadow_task_name or task_name + def _get_meta_from_request(self, request=None): """ Use the request or get_current_task to evaluate the `meta` attribute. diff --git a/t/unit/backends/test_database.py b/t/unit/backends/test_database.py index 8baa6cc0..85d84289 100644 --- a/t/unit/backends/test_database.py +++ b/t/unit/backends/test_database.py @@ -784,6 +784,7 @@ def test_on_chord_part_return(self): request.id = subtasks[0].id request.group = gid request.task = "my_task" + request.shadow = None request.args = ["a", 1, "password"] request.kwargs = {"c": 3, "d": "e", "password": "password"} request.argsrepr = "argsrepr" @@ -834,6 +835,7 @@ def test_callback_failure(self): request.id = subtasks[0].id request.group = gid request.task = "my_task" + request.shadow = None request.args = ["a", 1, "password"] request.kwargs = {"c": 3, "d": "e", "password": "password"} request.argsrepr = "argsrepr" @@ -880,6 +882,7 @@ def test_on_chord_part_return_failure(self): request.id = tid1 request.group = gid request.task = "my_task" + request.shadow = None request.args = ["a", 1, "password"] request.kwargs = {"c": 3, "d": "e", "password": "password"} request.argsrepr = "argsrepr" @@ -1026,6 +1029,7 @@ def test_on_chord_part_return_multiple_databases(self): request.id = subtasks[0].id request.group = gid request.task = "my_task" + request.shadow = None request.args = ["a", 1, "password"] request.kwargs = {"c": 3, "d": "e", "password": "password"} request.argsrepr = "argsrepr"