Utilities¶
Utility functions for creating and managing tasks.
API Reference¶
utils
¶
TaskNotAllowedError
¶
Bases: Exception
Raised when attempting to create a task that is not in the allowed list.
create_task(task: str, args: dict) -> uuid.UUID
¶
Create a new task to be executed by the worker.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
task
|
str
|
Dotted path to the callable (e.g., "myapp.tasks.process_order") |
required |
args
|
dict
|
Dictionary of keyword arguments to pass to the callable |
required |
Returns:
| Type | Description |
|---|---|
UUID
|
UUID of the created task |
Raises:
| Type | Description |
|---|---|
TypeError
|
If args is not a dict |
TaskNotAllowedError
|
If task is not in DJANGO_SIMPLE_QUEUE_ALLOWED_TASKS |
Example
from django_simple_queue.utils import create_task
task_id = create_task( task="myapp.tasks.send_email", args={"to": "user@example.com", "subject": "Hello"} )
Source code in django_simple_queue/utils.py
create_task¶
The primary way to enqueue tasks for background execution.
Signature¶
Parameters¶
| Parameter | Type | Description |
|---|---|---|
task |
str | Dotted path to the callable (e.g., "myapp.tasks.send_email") |
args |
dict | Keyword arguments to pass to the callable |
Returns¶
UUID: The unique identifier of the created task
Raises¶
TypeError: Ifargsis not a dictionaryTaskNotAllowedError: If task is not inDJANGO_SIMPLE_QUEUE_ALLOWED_TASKS
Examples¶
from django_simple_queue.utils import create_task
# Basic usage
task_id = create_task(
task="myapp.tasks.send_email",
args={"to": "user@example.com", "subject": "Hello"}
)
# With complex arguments
task_id = create_task(
task="myapp.tasks.process_order",
args={
"order_id": 12345,
"options": {
"notify": True,
"priority": "high"
}
}
)
# Check the created task
from django_simple_queue.models import Task
task = Task.objects.get(id=task_id)
print(task.status) # 0 (QUEUED)
TaskNotAllowedError¶
Exception raised when attempting to create a task that is not in the allowlist.
Example¶
from django_simple_queue.utils import create_task, TaskNotAllowedError
try:
task_id = create_task(
task="some.unknown.function",
args={}
)
except TaskNotAllowedError as e:
print(f"Task not allowed: {e}")
Best Practices¶
Pass IDs, Not Objects¶
# Good
create_task(
task="myapp.tasks.process_user",
args={"user_id": user.id}
)
# Bad - can't serialize model instances
create_task(
task="myapp.tasks.process_user",
args={"user": user} # TypeError!
)