django-tasks


Namedjango-tasks JSON
Version 0.6.0 PyPI version JSON
download
home_pageNone
SummaryAn implementation and backport of background workers and tasks in Django
upload_time2024-11-29 17:13:30
maintainerNone
docs_urlNone
authorJake Howard
requires_python>=3.8
licenseCopyright (c) Jake Howard and individual contributors. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # Django Tasks

[![CI](https://github.com/RealOrangeOne/django-tasks/actions/workflows/ci.yml/badge.svg)](https://github.com/RealOrangeOne/django-tasks/actions/workflows/ci.yml)
![PyPI](https://img.shields.io/pypi/v/django-tasks.svg)
![PyPI - Python Version](https://img.shields.io/pypi/pyversions/django-tasks.svg)
![PyPI - Status](https://img.shields.io/pypi/status/django-tasks.svg)
![PyPI - License](https://img.shields.io/pypi/l/django-tasks.svg)

An implementation and backport of background workers and tasks in Django, as defined in [DEP 0014](https://github.com/django/deps/blob/main/accepted/0014-background-workers.rst).

**Warning**: This package is under active development, and breaking changes may be released at any time. Be sure to pin to specific 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`.

```python
INSTALLED_APPS = [
    # ...
    "django_tasks",
]
```

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:

```python
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](https://github.com/django/deps/blob/main/accepted/0014-background-workers.rst). [The tests](./tests/tests/) are also a good exhaustive reference.

### Defining tasks

A task is created with the `task` decorator.

```python
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`)
- `enqueue_on_commit`: Whether the task is enqueued when the current transaction commits successfully, or enqueued immediately. By default, this is handled by the backend (see below). `enqueue_on_commit` may not be modified with `.using`.

These attributes (besides `enqueue_on_commit`) can also be modified at run-time with `.using`:

```python
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.

### Enqueueing tasks

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

```python
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`.

#### Transactions

By default, tasks are enqueued after the current transaction (if there is one) commits successfully (using Django's `transaction.on_commit` method), rather than enqueueing immediately.

This can be configured using the `ENQUEUE_ON_COMMIT` setting. `True` and `False` force the behaviour.

```python
TASKS = {
    "default": {
        "BACKEND": "django_tasks.backends.immediate.ImmediateBackend",
        "ENQUEUE_ON_COMMIT": False
    }
}
```

This can also be configured per-task by passing `enqueue_on_commit` to the `task` decorator.

### 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.

```python
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`:

```python
INSTALLED_APPS = [
    # ...
    "django_tasks",
    "django_tasks.backends.database",
]
```

Then, run migrations:

```shell
./manage.py migrate
```

Next, configure the database backend:

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

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

```shell
./manage.py db_worker
```

### Pruning old tasks

After a while, tasks may start to build up in your database. This can be managed using the `prune_db_task_results` management command, which deletes completed tasks according to the given retention policy. Check the `--help` for the available 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`):

```python
result_id = result.id

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

A result `id` should be considered an opaque string, whose length could be up to 64 characters. ID generation is backend-specific.

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:

```python
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 `.return_value` attribute on a `TaskResult`. Accessing this property on an unfinished task (ie not `SUCCEEDED` or `FAILED`) will raise a `ValueError`.

```python
assert result.status == ResultStatus.SUCCEEDED
assert result.return_value == 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.

```python
assert result.status == ResultStatus.NEW
result.refresh()
assert result.status == ResultStatus.SUCCEEDED
```

#### Exceptions

If a task raised an exception, its `.exception_class` will be the exception class raised:

```python
assert result.exception == ValueError
```

Note that this is just the type of exception, and contains no other values. The traceback information is reduced to a string that you can print to help debugging:

```python
assert isinstance(result.traceback, str)
```

### 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)?

```python
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](https://docs.djangoproject.com/en/stable/topics/checks/).

### Signals

A few [Signals](https://docs.djangoproject.com/en/stable/topics/signals/) are provided to more easily respond to certain task events.

Whilst signals are available, they may not be the most maintainable approach.

- `django_tasks.signals.task_enqueued`: Called when a task is enqueued. The sender is the backend class. Also called with the enqueued `task_result`.
- `django_tasks.signals.task_finished`: Called when a task finishes (`SUCCEEDED` or `FAILED`). The sender is the backend class. Also called with the finished `task_result`.

## Contributing

See [CONTRIBUTING.md](./CONTRIBUTING.md) for information on how to contribute.

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "django-tasks",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.8",
    "maintainer_email": null,
    "keywords": null,
    "author": "Jake Howard",
    "author_email": null,
    "download_url": "https://files.pythonhosted.org/packages/ba/ac/3b8a28845eba5e5160c2444098bd933642371c479bed96c40fd5de56bf0a/django_tasks-0.6.0.tar.gz",
    "platform": null,
    "description": "# Django Tasks\n\n[![CI](https://github.com/RealOrangeOne/django-tasks/actions/workflows/ci.yml/badge.svg)](https://github.com/RealOrangeOne/django-tasks/actions/workflows/ci.yml)\n![PyPI](https://img.shields.io/pypi/v/django-tasks.svg)\n![PyPI - Python Version](https://img.shields.io/pypi/pyversions/django-tasks.svg)\n![PyPI - Status](https://img.shields.io/pypi/status/django-tasks.svg)\n![PyPI - License](https://img.shields.io/pypi/l/django-tasks.svg)\n\nAn implementation and backport of background workers and tasks in Django, as defined in [DEP 0014](https://github.com/django/deps/blob/main/accepted/0014-background-workers.rst).\n\n**Warning**: This package is under active development, and breaking changes may be released at any time. Be sure to pin to specific versions if you're using this package in a production environment.\n\n## Installation\n\n```\npython -m pip install django-tasks\n```\n\nThe first step is to add `django_tasks` to your `INSTALLED_APPS`.\n\n```python\nINSTALLED_APPS = [\n    # ...\n    \"django_tasks\",\n]\n```\n\nSecondly, you'll need to configure a backend. This connects the tasks to whatever is going to execute them.\n\nIf omitted, the following configuration is used:\n\n```python\nTASKS = {\n    \"default\": {\n        \"BACKEND\": \"django_tasks.backends.immediate.ImmediateBackend\"\n    }\n}\n```\n\nA few backends are included by default:\n\n- `django_tasks.backends.dummy.DummyBackend`: Don't execute the tasks, just store them. This is especially useful for testing.\n- `django_tasks.backends.immediate.ImmediateBackend`: Execute the task immediately in the current thread\n- `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\n\nNote: `DatabaseBackend` additionally requires `django_tasks.backends.database` adding to `INSTALLED_APPS`.\n\n## Usage\n\n**Note**: This documentation is still work-in-progress. Further details can also be found on the [DEP](https://github.com/django/deps/blob/main/accepted/0014-background-workers.rst). [The tests](./tests/tests/) are also a good exhaustive reference.\n\n### Defining tasks\n\nA task is created with the `task` decorator.\n\n```python\nfrom django_tasks import task\n\n\n@task()\ndef calculate_meaning_of_life() -> int:\n    return 42\n```\n\nThe task decorator accepts a few arguments to customize the task:\n\n- `priority`: The priority of the task (between -100 and 100. Larger numbers are higher priority. 0 by default)\n- `queue_name`: Whether to run the task on a specific queue\n- `backend`: Name of the backend for this task to use (as defined in `TASKS`)\n- `enqueue_on_commit`: Whether the task is enqueued when the current transaction commits successfully, or enqueued immediately. By default, this is handled by the backend (see below). `enqueue_on_commit` may not be modified with `.using`.\n\nThese attributes (besides `enqueue_on_commit`) can also be modified at run-time with `.using`:\n\n```python\nmodified_task = calculate_meaning_of_life.using(priority=10)\n```\n\nIn addition to the above attributes, `run_after` can be passed to specify a specific time the task should run.\n\n### Enqueueing tasks\n\nTo execute a task, call the `enqueue` method on it:\n\n```python\nresult = calculate_meaning_of_life.enqueue()\n```\n\nThe returned `TaskResult` can be interrogated to query the current state of the running task, as well as its return value.\n\nIf the task takes arguments, these can be passed as-is to `enqueue`.\n\n#### Transactions\n\nBy default, tasks are enqueued after the current transaction (if there is one) commits successfully (using Django's `transaction.on_commit` method), rather than enqueueing immediately.\n\nThis can be configured using the `ENQUEUE_ON_COMMIT` setting. `True` and `False` force the behaviour.\n\n```python\nTASKS = {\n    \"default\": {\n        \"BACKEND\": \"django_tasks.backends.immediate.ImmediateBackend\",\n        \"ENQUEUE_ON_COMMIT\": False\n    }\n}\n```\n\nThis can also be configured per-task by passing `enqueue_on_commit` to the `task` decorator.\n\n### Queue names\n\nBy 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.\n\n```python\nTASKS = {\n    \"default\": {\n        \"BACKEND\": \"django_tasks.backends.immediate.ImmediateBackend\",\n        \"QUEUES\": [\"default\", \"special\"]\n    }\n}\n```\n\nEnqueueing tasks to an unknown queue name raises `InvalidTaskError`.\n\nTo disable queue name validation, set `QUEUES` to `[]`.\n\n### The database backend worker\n\nFirst, you'll need to add `django_tasks.backends.database`  to `INSTALLED_APPS`:\n\n```python\nINSTALLED_APPS = [\n    # ...\n    \"django_tasks\",\n    \"django_tasks.backends.database\",\n]\n```\n\nThen, run migrations:\n\n```shell\n./manage.py migrate\n```\n\nNext, configure the database backend:\n\n```python\nTASKS = {\n    \"default\": {\n        \"BACKEND\": \"django_tasks.backends.database.DatabaseBackend\"\n    }\n}\n```\n\nFinally, you can run the `db_worker` command to run tasks as they're created. Check the `--help` for more options.\n\n```shell\n./manage.py db_worker\n```\n\n### Pruning old tasks\n\nAfter a while, tasks may start to build up in your database. This can be managed using the `prune_db_task_results` management command, which deletes completed tasks according to the given retention policy. Check the `--help` for the available options.\n\n### Retrieving task result\n\nWhen 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`):\n\n```python\nresult_id = result.id\n\n# Later, somewhere else...\ncalculate_meaning_of_life.get_result(result_id)\n```\n\nA result `id` should be considered an opaque string, whose length could be up to 64 characters. ID generation is backend-specific.\n\nOnly 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:\n\n```python\nfrom django_tasks import default_task_backend\n\ndefault_task_backend.get_result(result_id)\n```\n\n### Return values\n\nIf your task returns something, it can be retrieved from the `.return_value` attribute on a `TaskResult`. Accessing this property on an unfinished task (ie not `SUCCEEDED` or `FAILED`) will raise a `ValueError`.\n\n```python\nassert result.status == ResultStatus.SUCCEEDED\nassert result.return_value == 42\n```\n\nIf 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.\n\n```python\nassert result.status == ResultStatus.NEW\nresult.refresh()\nassert result.status == ResultStatus.SUCCEEDED\n```\n\n#### Exceptions\n\nIf a task raised an exception, its `.exception_class` will be the exception class raised:\n\n```python\nassert result.exception == ValueError\n```\n\nNote that this is just the type of exception, and contains no other values. The traceback information is reduced to a string that you can print to help debugging:\n\n```python\nassert isinstance(result.traceback, str)\n```\n\n### Backend introspecting\n\nBecause `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.\n\n- `supports_defer`: Can tasks be enqueued with the `run_after` attribute?\n- `supports_async_task`: Can coroutines be enqueued?\n- `supports_get_result`: Can results be retrieved after the fact (from **any** thread / process)?\n\n```python\nfrom django_tasks import default_task_backend\n\nassert default_task_backend.supports_get_result\n```\n\nThis is particularly useful in combination with Django's [system check framework](https://docs.djangoproject.com/en/stable/topics/checks/).\n\n### Signals\n\nA few [Signals](https://docs.djangoproject.com/en/stable/topics/signals/) are provided to more easily respond to certain task events.\n\nWhilst signals are available, they may not be the most maintainable approach.\n\n- `django_tasks.signals.task_enqueued`: Called when a task is enqueued. The sender is the backend class. Also called with the enqueued `task_result`.\n- `django_tasks.signals.task_finished`: Called when a task finishes (`SUCCEEDED` or `FAILED`). The sender is the backend class. Also called with the finished `task_result`.\n\n## Contributing\n\nSee [CONTRIBUTING.md](./CONTRIBUTING.md) for information on how to contribute.\n",
    "bugtrack_url": null,
    "license": "Copyright (c) Jake Howard and individual contributors. All rights reserved.  Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:  1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.  2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.  3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ",
    "summary": "An implementation and backport of background workers and tasks in Django",
    "version": "0.6.0",
    "project_urls": {
        "Changelog": "https://github.com/RealOrangeOne/django-tasks/releases",
        "Issues": "https://github.com/RealOrangeOne/django-tasks/issues",
        "Source": "https://github.com/RealOrangeOne/django-tasks"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "52302c3df5cbed14cd2ae51b14ad44614d36eac6f7c487dc4a629df9bd75d6e1",
                "md5": "919c4bc7b604288cf8c86ec768a4594f",
                "sha256": "5dc9f4738da164291417c6be2731c7e12265b2be725e8b229c0f10cfed87027c"
            },
            "downloads": -1,
            "filename": "django_tasks-0.6.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "919c4bc7b604288cf8c86ec768a4594f",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8",
            "size": 36225,
            "upload_time": "2024-11-29T17:13:28",
            "upload_time_iso_8601": "2024-11-29T17:13:28.305849Z",
            "url": "https://files.pythonhosted.org/packages/52/30/2c3df5cbed14cd2ae51b14ad44614d36eac6f7c487dc4a629df9bd75d6e1/django_tasks-0.6.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "baac3b8a28845eba5e5160c2444098bd933642371c479bed96c40fd5de56bf0a",
                "md5": "41dad17ed2f7658846b31c4616c669c5",
                "sha256": "f038d5c4d2e4b0d8139ee246247092aae623719569209fea8c38f79519396d79"
            },
            "downloads": -1,
            "filename": "django_tasks-0.6.0.tar.gz",
            "has_sig": false,
            "md5_digest": "41dad17ed2f7658846b31c4616c669c5",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8",
            "size": 26496,
            "upload_time": "2024-11-29T17:13:30",
            "upload_time_iso_8601": "2024-11-29T17:13:30.425614Z",
            "url": "https://files.pythonhosted.org/packages/ba/ac/3b8a28845eba5e5160c2444098bd933642371c479bed96c40fd5de56bf0a/django_tasks-0.6.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-11-29 17:13:30",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "RealOrangeOne",
    "github_project": "django-tasks",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "django-tasks"
}
        
Elapsed time: 0.76842s