1
0
mirror of https://github.com/django/django.git synced 2025-04-04 21:46:40 +00:00

Serialize arguments in task, rather than each backend

This avoids duplication, and makes backend implementations simpler
This commit is contained in:
Jake Howard 2024-11-22 14:58:49 +00:00
parent 47fd467bba
commit f2046bd7c3
No known key found for this signature in database
GPG Key ID: 57AFB45680EDD477
4 changed files with 24 additions and 8 deletions

View File

@ -5,7 +5,7 @@ from django.db import transaction
from django.tasks.exceptions import ResultDoesNotExist
from django.tasks.signals import task_enqueued
from django.tasks.task import ResultStatus, TaskResult
from django.tasks.utils import get_random_id, json_normalize
from django.tasks.utils import get_random_id
from django.utils import timezone
from .base import BaseTaskBackend
@ -35,8 +35,8 @@ class DummyBackend(BaseTaskBackend):
enqueued_at=None,
started_at=None,
finished_at=None,
args=json_normalize(args),
kwargs=json_normalize(kwargs),
args=args,
kwargs=kwargs,
backend=self.alias,
)

View File

@ -70,8 +70,8 @@ class ImmediateBackend(BaseTaskBackend):
enqueued_at=None,
started_at=None,
finished_at=None,
args=json_normalize(args),
kwargs=json_normalize(kwargs),
args=args,
kwargs=kwargs,
backend=self.alias,
)

View File

@ -10,7 +10,7 @@ from django.utils import timezone
from django.utils.translation import gettext_lazy as _
from .exceptions import ResultDoesNotExist
from .utils import exception_from_dict, get_module_path
from .utils import exception_from_dict, get_module_path, json_normalize
DEFAULT_TASK_BACKEND_ALIAS = "default"
DEFAULT_QUEUE_NAME = "default"
@ -100,13 +100,17 @@ class Task:
"""
Queue up the task to be executed
"""
return self.get_backend().enqueue(self, args, kwargs)
return self.get_backend().enqueue(
self, json_normalize(args), json_normalize(kwargs)
)
async def aenqueue(self, *args, **kwargs):
"""
Queue up a task function (or coroutine) to be executed
"""
return await self.get_backend().aenqueue(self, args, kwargs)
return await self.get_backend().aenqueue(
self, json_normalize(args), json_normalize(kwargs)
)
def get_result(self, result_id):
"""

View File

@ -68,6 +68,18 @@ class TaskTestCase(SimpleTestCase):
self.assertEqual(default_task_backend.results, [result])
def test_enqueue_with_invalid_argument(self):
with self.assertRaisesMessage(
TypeError, "Object of type datetime is not JSON serializable"
):
test_tasks.noop_task.enqueue(datetime.now())
async def test_aenqueue_with_invalid_argument(self):
with self.assertRaisesMessage(
TypeError, "Object of type datetime is not JSON serializable"
):
await test_tasks.noop_task.aenqueue(datetime.now())
def test_using_priority(self):
self.assertEqual(test_tasks.noop_task.priority, 0)
self.assertEqual(test_tasks.noop_task.using(priority=1).priority, 1)