|
1 | 1 | from dataclasses import asdict, dataclass |
2 | | -from typing import TYPE_CHECKING, Any, List, TypeVar |
| 2 | +from typing import TYPE_CHECKING, Any, Iterable, TypeVar |
3 | 3 |
|
4 | 4 | from django.apps import apps |
5 | | -from django.core.checks import ERROR, CheckMessage |
| 5 | +from django.core.checks import messages |
6 | 6 | from django.core.exceptions import ValidationError |
7 | 7 | from typing_extensions import ParamSpec |
8 | 8 |
|
9 | 9 | from django_tasks.backends.base import BaseTaskBackend |
10 | | -from django_tasks.exceptions import ResultDoesNotExist |
| 10 | +from django_tasks.exceptions import InvalidTaskError, ResultDoesNotExist |
11 | 11 | from django_tasks.task import Task |
12 | 12 | from django_tasks.task import TaskResult as BaseTaskResult |
13 | 13 | from django_tasks.utils import json_normalize |
@@ -39,6 +39,14 @@ class DatabaseBackend(BaseTaskBackend): |
39 | 39 | supports_get_result = True |
40 | 40 | supports_defer = True |
41 | 41 |
|
| 42 | + def validate_task(self, task: Task[P, T]) -> None: |
| 43 | + super().validate_task(task) |
| 44 | + |
| 45 | + if task.enqueue_on_commit is False: |
| 46 | + raise InvalidTaskError( |
| 47 | + "enqueue_on_commit must be True or None when using database backend" |
| 48 | + ) |
| 49 | + |
42 | 50 | def _task_to_db_task( |
43 | 51 | self, task: Task[P, T], args: P.args, kwargs: P.kwargs |
44 | 52 | ) -> "DBTaskResult": |
@@ -91,16 +99,21 @@ async def aget_result(self, result_id: str) -> TaskResult: |
91 | 99 | except (DBTaskResult.DoesNotExist, ValidationError) as e: |
92 | 100 | raise ResultDoesNotExist(result_id) from e |
93 | 101 |
|
94 | | - def check(self, **kwargs: Any) -> List[CheckMessage]: |
95 | | - if not apps.is_installed("django_tasks.backends.database"): |
96 | | - backend_name = self.__class__.__name__ |
| 102 | + def check(self, **kwargs: Any) -> Iterable[messages.CheckMessage]: |
| 103 | + yield from super().check(**kwargs) |
97 | 104 |
|
98 | | - return [ |
99 | | - CheckMessage( |
100 | | - ERROR, |
101 | | - f"{backend_name} configured as django_tasks backend, but database app not installed", |
102 | | - "Insert 'django_tasks.backends.database' in INSTALLED_APPS", |
103 | | - ) |
104 | | - ] |
| 105 | + backend_name = self.__class__.__name__ |
105 | 106 |
|
106 | | - return [] |
| 107 | + if not apps.is_installed("django_tasks.backends.database"): |
| 108 | + yield messages.CheckMessage( |
| 109 | + messages.ERROR, |
| 110 | + f"{backend_name} configured as django_tasks backend, but database app not installed", |
| 111 | + "Insert 'django_tasks.backends.database' in INSTALLED_APPS", |
| 112 | + ) |
| 113 | + |
| 114 | + if self.enqueue_on_commit is False: |
| 115 | + yield messages.CheckMessage( |
| 116 | + messages.WARNING, |
| 117 | + f"{backend_name} must enqueue tasks at the end of a transaction", |
| 118 | + "Ensure ENQUEUE_ON_COMMIT is True or None", |
| 119 | + ) |
0 commit comments