Example project for the Real Python tutorial Django Tasks: Exploring the Built-in Tasks Framework.
The project demonstrates Django 6's @task decorator, the django-tasks-db database-backed worker, named queues with priorities, and the transaction.on_commit pattern for safe enqueueing inside an atomic block.
Set up a virtual environment and install dependencies:
$ python -m venv venv
$ source venv/bin/activate
(venv) $ python -m pip install -r requirements.txtRun migrations:
(venv) $ python -m manage makemigrations myapp
(venv) $ python -m manage migrateThe project uses two processes: the Django dev server and the db_worker.
In one terminal, start the worker:
(venv) $ python -m manage db_worker --queue-name '*'In a second terminal, start the dev server:
(venv) $ python -m manage runserverTrigger the demo endpoints with curl or your browser:
$ curl 'http://localhost:8000/register/?email=alice@example.com&name=Alice'
$ curl http://localhost:8000/checkout/
$ curl http://localhost:8000/task-status/<task-id>/You can also enqueue tasks from the Django shell:
(venv) $ python -m manage shell>>> from myapp.tasks import say_hello
>>> result = say_hello.enqueue("Real Python")
>>> result.refresh()
>>> result.status
SUCCESSFUL
>>> result.return_value
'Hello, Real Python!'