Skip to main content

A reference implementation and backport of background workers and tasks in Django

Project description

Django Tasks

CI PyPI PyPI - Python Version PyPI - Status PyPI - License

A reference implementation and backport of background workers and tasks in Django, as defined in DEP 0014.

Warning: This package is under active development, and breaking changes may be released at any time. Be sure to pin to specific versions (even patch versions) if you're using this package in a production environment.

Installation

python -m pip install django-tasks

The first step is to add django_tasks to your INSTALLED_APPS.

Secondly, you'll need to configure a backend. This connects the tasks to whatever is going to execute them.

If omitted, the following configuration is used:

TASKS = {
    "default": {
        "BACKEND": "django_tasks.backends.immediate.ImmediateBackend"
    }
}

A few backends are included by default:

  • django_tasks.backends.dummy.DummyBackend: Don't execute the tasks, just store them. This is especially useful for testing.
  • django_tasks.backends.immediate.ImmediateBackend: Execute the task immediately in the current thread
  • django_tasks.backends.database.DatabaseBackend: Store tasks in the database (via Django's ORM), and retrieve and execute them using the db_worker management command

Note: DatabaseBackend additionally requires django_tasks.backends.database adding to INSTALLED_APPS.

Usage

Note: This documentation is still work-in-progress. Further details can also be found on the DEP. The tests are also a good exhaustive reference.

Defining tasks

A task is created with the task decorator.

from django_tasks import task


@task()
def calculate_meaning_of_life() -> int:
    return 42

The task decorator accepts a few arguments to customize the task:

  • priority: The priority of the task (between -100 and 100. Larger numbers are higher priority. 0 by default)
  • queue_name: Whether to run the task on a specific queue
  • backend: Name of the backend for this task to use (as defined in TASKS)

These attributes can also be modified at run-time with .using:

modified_task = calculate_meaning_of_life.using(priority=10)

In addition to the above attributes, run_after can be passed to specify a specific time the task should run. Both a timezone-aware datetime or timedelta may be passed.

Enqueueing tasks

To execute a task, call the enqueue method on it:

result = calculate_meaning_of_life.enqueue()

The returned TaskResult can be interrogated to query the current state of the running task, as well as its return value.

If the task takes arguments, these can be passed as-is to enqueue.

Queue names

By default, tasks are enqueued onto the "default" queue. When using multiple queues, it can be useful to constrain the allowed names, so tasks aren't missed.

TASKS = {
    "default": {
        "BACKEND": "django_tasks.backends.immediate.ImmediateBackend",
        "QUEUES": ["default", "special"]
    }
}

Enqueueing tasks to an unknown queue name raises InvalidTaskError.

To disable queue name validation, set QUEUES to [].

The database backend worker

First, you'll need to add django_tasks.backends.database to INSTALLED_APPS, and run manage.py migrate.

Next, configure the database backend:

TASKS = {
    "default": {
        "BACKEND": "django_tasks.backends.database.DatabaseBackend"
    }
}

Finally, you can run manage.py db_worker to run tasks as they're created. Check the --help for more options.

Retrieving task result

When enqueueing a task, you get a TaskResult, however it may be useful to retrieve said result from somewhere else (another request, another task etc). This can be done with get_result (or aget_result):

result_id = result.id

# Later, somewhere else...
calculate_meaning_of_life.get_result(result_id)

Only tasks of the same type can be retrieved this way. To retrieve the result of any task, you can call get_result on the backend:

from django_tasks import default_task_backend

default_task_backend.get_result(result_id)

Return values

If your task returns something, it can be retrieved from the .result attribute on a TaskResult. Accessing this property on an unfinished task (ie not COMPLETE or FAILED) will raise a ValueError.

assert result.status == ResultStatus.COMPLETE
assert result.result == 42

If a result has been updated in the background, you can call refresh on it to update its values. Results obtained using get_result will always be up-to-date.

assert result.status == ResultStatus.NEW
result.refresh()
assert result.status == ResultStatus.COMPLETE

Exceptions

If a task raised an exception, its .result will be the exception raised:

assert isinstance(result.result, ValueError)

As part of the serialization process for exceptions, some information is lost. The traceback information is reduced to a string that you can print to help debugging:

assert isinstance(result.traceback, str)

The stack frames, globals() and locals() are not available.

If the exception could not be serialized, the .result is None.

Backend introspecting

Because django-tasks enables support for multiple different backends, those backends may not support all features, and it can be useful to determine this at runtime to ensure the chosen task queue meets the requirements, or to gracefully degrade functionality if it doesn't.

  • supports_defer: Can tasks be enqueued with the run_after attribute?
  • supports_async_task: Can coroutines be enqueued?
  • supports_get_result: Can results be retrieved after the fact (from any thread / process)?
from django_tasks import default_task_backend

assert default_task_backend.supports_get_result

This is particularly useful in combination with Django's system check framework.

Contributing

See CONTRIBUTING.md for information on how to contribute.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

django_tasks-0.3.0.tar.gz (21.9 kB view details)

Uploaded Source

Built Distribution

django_tasks-0.3.0-py3-none-any.whl (26.4 kB view details)

Uploaded Python 3

File details

Details for the file django_tasks-0.3.0.tar.gz.

File metadata

  • Download URL: django_tasks-0.3.0.tar.gz
  • Upload date:
  • Size: 21.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/5.1.0 CPython/3.12.4

File hashes

Hashes for django_tasks-0.3.0.tar.gz
Algorithm Hash digest
SHA256 3b246188de12c6e355f953fc5f4337b4b66f68471cab2245dc69da6c3089b0e4
MD5 19d9c4ab56a5fc747dfa859a767f3462
BLAKE2b-256 562119f7ad8bf1b37276a0590c018f4123f2eb717e80788ffe9c54730194c44e

See more details on using hashes here.

File details

Details for the file django_tasks-0.3.0-py3-none-any.whl.

File metadata

  • Download URL: django_tasks-0.3.0-py3-none-any.whl
  • Upload date:
  • Size: 26.4 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/5.1.0 CPython/3.12.4

File hashes

Hashes for django_tasks-0.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 1b4b2250b8e7ab09b3f5712e343c254b86a8cb94e59321456410371f5fcf7de2
MD5 8b11dc1f4f686636b1fbbb33d386d41c
BLAKE2b-256 0fd2355e3ae1f550145885cd9f556df4c732818af09e2e373e01ee45985e9414

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page