Skip to content

API reference

The public surface, from the models most projects touch down to the drivers. architecture explains how the layers fit together.

Models

Unmanaged Django models whose records live in Redis. task_id and group_id are the primary keys. Field names, verbose names, help texts and Meta options match django-celery-results; see parity.

Models stored in Redis.

The models are unmanaged: Django never creates tables for them. Saving and deleting go to the configured Redis store, and objects returns a RedisQuerySet, so the admin, forms and signals work as with database models.

TaskResult

Bases: RedisModel

Task result/status.

GroupResult

Bases: RedisModel

Task Group result/status.

ChordCounter

Bases: RedisModel

Chord synchronisation.

group_result

group_result(app=None)

Return the :class:celery.result.GroupResult of self.

Parameters:

Name Type Description Default
app Celery

app instance to create the :class:celery.result.GroupResult with.

None

Managers

TaskResult.objects, GroupResult.objects and ChordCounter.objects. They carry the methods the backend calls, plus delete_expired() for cleanup.

Model managers.

ResultManager

Bases: RedisManager

Generic manager for celery results.

store

store(pk, fields)

Create or update one record and return the instance.

Saving an instance costs a read and a write. When nothing listens for the model's save signals, the record is written in a single round trip instead, which is the path Celery workers take for every state change.

get_all_expired

get_all_expired(expires)

Get all expired results.

delete_expired

delete_expired(expires)

Delete all expired results.

TaskResultManager

Bases: ResultManager

Manager for :class:~.models.TaskResult models.

get_task

get_task(task_id)

Get result for task by task_id, or an unsaved instance.

store_result

store_result(
    content_type,
    content_encoding,
    task_id,
    result,
    status,
    traceback=None,
    meta=None,
    periodic_task_name=None,
    task_name=None,
    task_args=None,
    task_kwargs=None,
    worker=None,
    using=None,
    **kwargs,
)

Store the result and status of a task.

Parameters:

Name Type Description Default
content_type str

Mime-type of result and meta content.

required
content_encoding str

Type of encoding (e.g. binary/utf-8).

required
task_id str

Id of task.

required
periodic_task_name str

Celery Periodic task name.

None
task_name str

Celery task name.

None
task_args str

Task arguments.

None
task_kwargs str

Task kwargs.

None
result str

The serialized return value of the task, or an exception instance raised by the task.

required
status str

Task status. See :mod:celery.states for a list of possible status values.

required
worker str

Worker that executes the task.

None
using str

Accepted for compatibility; ignored.

None
traceback str

The traceback string taken at the point of exception (only passed if the task failed).

None
meta str

Serialized result meta data (this contains e.g. children).

None

Other Parameters:

Name Type Description
date_started datetime

When the task started.

exception_retry_count int

How many times to retry on Redis connection errors. The default is to retry twice.

GroupResultManager

Bases: ResultManager

Manager for :class:~.models.GroupResult models.

get_group

get_group(group_id)

Get result for group by group_id, or an unsaved instance.

ChordCounterManager

Bases: RedisManager

Manager for :class:~.models.ChordCounter models.

decrement

decrement(group_id)

Atomically decrement the counter of group_id.

Returns None if there is no counter. Otherwise returns an unsaved instance holding the remaining count; once the count reaches zero the counter is deleted and the instance carries its sub_tasks.

transaction_retry

transaction_retry(max_retries=1)

Retry the decorated function on Redis connection errors.

Other Parameters:

Name Type Description
max_retries int

Maximum number of retries. Default one retry. Callers can override it with exception_retry_count.

Backend

The Celery result backend. Registered as django-redis-db in the celery.result_backends entry point group, so CELERY_RESULT_BACKEND = "django-redis-db" is enough.

Celery result backend storing results through the Redis models.

RedisResultBackend

Bases: BaseDictBackend

Result backend using the Redis-stored models to keep task state.

exception_safe_to_retry

exception_safe_to_retry(exc)

Check if an exception is safe to retry.

Redis connection and timeout errors are retried when result_backend_always_retry is enabled; the connection pool opens a new connection on the next attempt.

cleanup

cleanup()

Delete expired metadata.

apply_chord

apply_chord(header_result_args, body, **kwargs)

Add a ChordCounter with the expected number of results.

on_chord_part_return

on_chord_part_return(request, state, result, **kwargs)

Called on finishing each part of a Chord header.

trigger_callback

trigger_callback(app, callback, group_result)

Add the callback to the queue or mark the callback as failed.

Implementation borrowed from celery.app.builtins.unlock_chord

QuerySet

What the managers return. It subclasses django.db.models.QuerySet and implements the parts that can be answered from Redis; everything else raises NotSupportedError. See parity for the supported lookups.

A QuerySet whose rows live in Redis.

RedisQuerySet subclasses Django's QuerySet so that code checking isinstance(obj, QuerySet) (the admin does) keeps working. Its query is a RedisQuery holding a lookup tree instead of SQL. Methods that only use the public query API (filter, exclude, order_by, get, slicing, ...) are inherited; methods that would build SQL are overridden or raise NotSupportedError.

RedisQuerySet

Bases: QuerySet

RedisQuery

The query state of a RedisQuerySet.

Exposes the attributes of django.db.models.sql.Query that Django's QuerySet and admin read, with a lookup tree as where.

get_ordering

get_ordering()

The effective ordering, made total by a final primary key key.

RedisManager

Bases: from_queryset(RedisQuerySet)

Stores

One store per model, built from the settings by django_celery_results_redis.store.get_store(). Store is the base and the raw driver; the other two add query pushdown. A dotted path to a Store subclass is a valid value for the DRIVER setting, which is how a project can add its own.

Redis clients and per-model stores built from the app settings.

get_store

get_store(model)

Return the store of model for the configured driver.

get_client

get_client()

create_client

create_client()

create_sentinel_client

create_sentinel_client(url, kwargs)

Return the current master of a sentinel:// URL.

The URL lists the sentinels separated by ;, like Celery's sentinel result backend, for example sentinel://host-a:26379;sentinel://host-b:26379/0.

check_format_version

check_format_version(client, prefix)

Claim the key prefix for this format version, or refuse to use it.

reset

reset()

Drop the cached client and stores; the next access rebuilds them.

django_celery_results_redis.store.drivers.base.Store

maintains_index_fields property

maintains_index_fields

Whether records carry index fields besides their own.

index_payload

index_payload()

Index description passed to the Lua script, or None.

prepare

prepare()

Create server-side structures the driver needs (e.g. search indexes).

rebuild

rebuild()

Recreate the driver's indexes from the stored records.

index_values

index_values(pk, values)

Index fields to write for values, including the primary key.

renamed_index_values

renamed_index_values(new_pk)

Index fields a rename has to rewrite for the new primary key.

read

read(values)

Build a record from the values of field_names, or None.

get_many

get_many(pks)

Return the records of pks that exist, in the order given.

write

write(pk, values, *, mode='upsert', on_create=None)

Store values (None clears a field) for the record pk.

mode is "upsert", "insert" (fails if the record exists) or "update" (does nothing if it does not). on_create values are only written when the record is created. Returns (created, record), or None when an update found no record.

write_many

write_many(items)

Write (pk, values) pairs, one round trip per batch.

Values are stored as given: no automatic timestamps are applied, which is what importing existing results needs.

rename

rename(pk, new_pk)

Move record pk to new_pk; returns False if pk is missing.

decrement_counter

decrement_counter(pk)

Decrement a chord counter.

Returns None if the counter does not exist, otherwise (remaining, sub_tasks). sub_tasks is only returned, and the counter deleted, once remaining reaches zero.

candidate_records

candidate_records(where)

Yield a superset of the records matching where.

django_celery_results_redis.store.drivers.indexed.IndexedStore

Bases: PushdownStore

can_push

can_push(condition)

selection

selection(pushed, order_field=None)

repair

repair(pks)

Remove index entries of pks whose records no longer exist.

rebuild

rebuild()

distinct_values

distinct_values(where, field)

django_celery_results_redis.store.drivers.redis_om.RedisOMStore

Bases: PushdownStore

prepare

prepare()

ensure_index

ensure_index()

Create the search index, or recreate it if its schema changed.

rebuild

rebuild()

can_push

can_push(condition)

selection

selection(pushed, order_field=None)

distinct_values

distinct_values(where, field)

Read the distinct values of a tag field from the value counters.

Search index

Optional. Built when SEARCH is set, used by every driver. See drivers.

Optional RediSearch index for substring searches.

RediSearch matches whole tags and tokens, and its wildcard matching is capped by MAXEXPANSIONS, so neither can answer icontains exactly. This index instead stores the trigrams of each searchable field. A term matches only records holding every trigram of that term, which is a superset of the real matches: the store evaluates the lookup itself on the records the index returns, so the result is exactly what the in-memory evaluator would give.

Values longer than SEARCH_MAX_TEXT are not tokenized; their field is marked as overflowing instead, which keeps the record in every candidate set for that field.

SearchIndex

Trigram index over the searchable fields of one model.

index_values

index_values(values)

Return the index fields to write for the record fields in values.

candidates

candidates(where)

Return the primary keys that can match where, or None.

None means the index cannot narrow the query down, and the caller has to read every record.

tokens

tokens(text)

Return the trigram tokens of text, case-insensitively.

Settings

app_settings reads DJANGO_CELERY_RESULTS_REDIS on every access, so override_settings works in tests. settings documents each key.

Access to the DJANGO_CELERY_RESULTS_REDIS setting.

SETTING_NAME module-attribute

SETTING_NAME = 'DJANGO_CELERY_RESULTS_REDIS'

DEFAULTS module-attribute

DEFAULTS = {
    "DRIVER": "indexed",
    "URL": "redis://localhost:6379/0",
    "CLIENT_KWARGS": {},
    "CLIENT_FACTORY": None,
    "KEY_PREFIX": "dcrr",
    "ALLOW_EDITS": None,
    "TASK_ID_MAX_LENGTH": None,
    "SCAN_COUNT": 1000,
    "BATCH_SIZE": 500,
    "RESULT_TTL": None,
    "ID_FIRST_URLS": False,
    "SEARCH": None,
    "SEARCH_MAX_TEXT": 4096,
    "SEARCH_MAX_CANDIDATES": 50000,
    "SENTINEL_MASTER_NAME": "mymaster",
    "SENTINEL_KWARGS": {},
}

AppSettings

Read the setting on every access so override_settings is honoured.

allow_edits property

allow_edits

ALLOW_EDITS, falling back to the django-celery-results setting.

task_id_max_length property

task_id_max_length

TASK_ID_MAX_LENGTH, falling back to the django-celery-results setting.

result_ttl property

result_ttl

RESULT_TTL in whole seconds, or None.