This document describes the current stable version of Celery (5.2). For development docs, go here.

celery.backends.rpc

The RPC result backend for AMQP brokers.

RPC-style result backend, using reply-to and one queue per client.

exception celery.backends.rpc.BacklogLimitExceeded[source]

Too much state history to fast-forward.

class celery.backends.rpc.RPCBackend(app, connection=None, exchange=None, exchange_type=None, persistent=None, serializer=None, auto_delete=True, **kwargs)[source]

Base class for the RPC result backend.

exception BacklogLimitExceeded

Exception raised when there are too many messages for a task id.

class Consumer(channel, queues=None, no_ack=None, auto_declare=None, callbacks=None, on_decode_error=None, on_message=None, accept=None, prefetch_count=None, tag_prefix=None)[source]

Consumer that requires manual declaration of queues.

auto_declare = False

By default all entities will be declared at instantiation, if you want to handle this manually you can set this to False.

class Exchange(name='', type='', channel=None, **kwargs)

An Exchange declaration.

Parameters:
name

Name of the exchange. Default is no name (the default exchange).

Type:

str

type

This description of AMQP exchange types was shamelessly stolen from the blog post `AMQP in 10 minutes: Part 4`_ by Rajith Attapattu. Reading this article is recommended if you’re new to amqp.

“AMQP defines four default exchange types (routing algorithms) that covers most of the common messaging use cases. An AMQP broker can also define additional exchange types, so see your broker manual for more information about available exchange types.

  • direct (default)

    Direct match between the routing key in the message, and the routing criteria used when a queue is bound to this exchange.

  • topic

    Wildcard match between the routing key and the routing pattern specified in the exchange/queue binding. The routing key is treated as zero or more words delimited by “.” and supports special wildcard characters. “*” matches a single word and “#” matches zero or more words.

  • fanout

    Queues are bound to this exchange with no arguments. Hence any message sent to this exchange will be forwarded to all queues bound to this exchange.

  • headers

    Queues are bound to this exchange with a table of arguments containing headers and values (optional). A special argument named “x-match” determines the matching algorithm, where “all” implies an AND (all pairs must match) and “any” implies OR (at least one pair must match).

    arguments is used to specify the arguments.

Type:

str

channel

The channel the exchange is bound to (if bound).

Type:

ChannelT

durable

Durable exchanges remain active when a server restarts. Non-durable exchanges (transient exchanges) are purged when a server restarts. Default is True.

Type:

bool

auto_delete

If set, the exchange is deleted when all queues have finished using it. Default is False.

Type:

bool

delivery_mode

The default delivery mode used for messages. The value is an integer, or alias string.

  • 1 or “transient”

    The message is transient. Which means it is stored in memory only, and is lost if the server dies or restarts.

  • 2 or “persistent” (default)

    The message is persistent. Which means the message is stored both in-memory, and on disk, and therefore preserved if the server dies or restarts.

The default value is 2 (persistent).

Type:

enum

arguments

Additional arguments to specify when the exchange is declared.

Type:

Dict

no_declare

Never declare this exchange (declare() does nothing).

Type:

bool

Message(body, delivery_mode=None, properties=None, **kwargs)

Create message instance to be sent with publish().

Parameters:
  • body (Any) – Message body.

  • delivery_mode (bool) – Set custom delivery mode. Defaults to delivery_mode.

  • priority (int) – Message priority, 0 to broker configured max priority, where higher is better.

  • content_type (str) – The messages content_type. If content_type is set, no serialization occurs as it is assumed this is either a binary object, or you’ve done your own serialization. Leave blank if using built-in serialization as our library properly sets content_type.

  • content_encoding (str) – The character set in which this object is encoded. Use “binary” if sending in raw binary objects. Leave blank if using built-in serialization as our library properly sets content_encoding.

  • properties (Dict) – Message properties.

  • headers (Dict) – Message headers.

PERSISTENT_DELIVERY_MODE = 2
TRANSIENT_DELIVERY_MODE = 1
attrs = (('name', None), ('type', None), ('arguments', None), ('durable', <class 'bool'>), ('passive', <class 'bool'>), ('auto_delete', <class 'bool'>), ('delivery_mode', <function Exchange.<lambda>>), ('no_declare', <class 'bool'>))
auto_delete = False
bind_to(exchange='', routing_key='', arguments=None, nowait=False, channel=None, **kwargs)

Bind the exchange to another exchange.

Parameters:

nowait (bool) – If set the server will not respond, and the call will not block waiting for a response. Default is False.

binding(routing_key='', arguments=None, unbind_arguments=None)
property can_cache_declaration

bool(x) -> bool

Returns True when the argument x is true, False otherwise. The builtins True and False are the only two instances of the class bool. The class bool is a subclass of the class int, and cannot be subclassed.

declare(nowait=False, passive=None, channel=None)

Declare the exchange.

Creates the exchange on the broker, unless passive is set in which case it will only assert that the exchange exists.

Argument:
nowait (bool): If set the server will not respond, and a

response will not be waited for. Default is False.

delete(if_unused=False, nowait=False)

Delete the exchange declaration on server.

Parameters:
  • if_unused (bool) – Delete only if the exchange has no bindings. Default is False.

  • nowait (bool) – If set the server will not respond, and a response will not be waited for. Default is False.

delivery_mode = None
durable = True
name = ''
no_declare = False
passive = False
publish(message, routing_key=None, mandatory=False, immediate=False, exchange=None)

Publish message.

Parameters:
  • message (Union[kombu.Message, str, bytes]) – Message to publish.

  • routing_key (str) – Message routing key.

  • mandatory (bool) – Currently not supported.

  • immediate (bool) – Currently not supported.

type = 'direct'
unbind_from(source='', routing_key='', nowait=False, arguments=None, channel=None)

Delete previously created exchange binding from the server.

class Producer(channel, exchange=None, routing_key=None, serializer=None, auto_declare=None, compression=None, on_return=None)

Message Producer.

Parameters:
  • channel (kombu.Connection, ChannelT) – Connection or channel.

  • exchange (kombu.entity.Exchange, str) – Optional default exchange.

  • routing_key (str) – Optional default routing key.

  • serializer (str) – Default serializer. Default is “json”.

  • compression (str) – Default compression method. Default is no compression.

  • auto_declare (bool) – Automatically declare the default exchange at instantiation. Default is True.

  • on_return (Callable) – Callback to call for undeliverable messages, when the mandatory or immediate arguments to publish() is used. This callback needs the following signature: (exception, exchange, routing_key, message). Note that the producer needs to drain events to use this feature.

auto_declare = True

By default, if a defualt exchange is set, that exchange will be declare when publishing a message.

property channel
close()
compression = None

Default compression method. Disabled by default.

property connection
declare()

Declare the exchange.

Note

This happens automatically at instantiation when the auto_declare flag is enabled.

exchange = None

Default exchange

maybe_declare(entity, retry=False, **retry_policy)

Declare exchange if not already declared during this session.

on_return = None

Basic return callback.

publish(body, routing_key=None, delivery_mode=None, mandatory=False, immediate=False, priority=0, content_type=None, content_encoding=None, serializer=None, headers=None, compression=None, exchange=None, retry=False, retry_policy=None, declare=None, expiration=None, timeout=None, **properties)

Publish message to the specified exchange.

Parameters:
  • body (Any) – Message body.

  • routing_key (str) – Message routing key.

  • delivery_mode (enum) – See delivery_mode.

  • mandatory (bool) – Currently not supported.

  • immediate (bool) – Currently not supported.

  • priority (int) – Message priority. A number between 0 and 9.

  • content_type (str) – Content type. Default is auto-detect.

  • content_encoding (str) – Content encoding. Default is auto-detect.

  • serializer (str) – Serializer to use. Default is auto-detect.

  • compression (str) – Compression method to use. Default is none.

  • headers (Dict) – Mapping of arbitrary headers to pass along with the message body.

  • exchange (kombu.entity.Exchange, str) – Override the exchange. Note that this exchange must have been declared.

  • declare (Sequence[EntityT]) – Optional list of required entities that must have been declared before publishing the message. The entities will be declared using maybe_declare().

  • retry (bool) – Retry publishing, or declaring entities if the connection is lost.

  • retry_policy (Dict) – Retry configuration, this is the keywords supported by ensure().

  • expiration (float) – A TTL in seconds can be specified per message. Default is no expiration.

  • timeout (float) – Set timeout to wait maximum timeout second for message to publish.

  • **properties (Any) – Additional message properties, see AMQP spec.

release()
revive(channel)

Revive the producer after connection loss.

routing_key = ''

Default routing key.

serializer = None

Default serializer to use. Default is JSON.

class Queue(name='', exchange=None, routing_key='', channel=None, bindings=None, on_declared=None, **kwargs)[source]

Queue that never caches declaration.

can_cache_declaration = False

Defines whether maybe_declare can skip declaring this entity twice.

class ResultConsumer(*args, **kwargs)
class Consumer(channel, queues=None, no_ack=None, auto_declare=None, callbacks=None, on_decode_error=None, on_message=None, accept=None, prefetch_count=None, tag_prefix=None)

Message consumer.

Parameters:
exception ContentDisallowed

Consumer does not allow this content-type.

accept = None

List of accepted content-types.

An exception will be raised if the consumer receives a message with an untrusted content type. By default all content-types are accepted, but not if kombu.disable_untrusted_serializers() was called, in which case only json is allowed.

add_queue(queue)

Add a queue to the list of queues to consume from.

Note

This will not start consuming from the queue, for that you will have to call consume() after.

auto_declare = True

By default all entities will be declared at instantiation, if you want to handle this manually you can set this to False.

callbacks = None

List of callbacks called in order when a message is received.

The signature of the callbacks must take two arguments: (body, message), which is the decoded message body and the Message instance.

cancel()

End all active queue consumers.

Note

This does not affect already delivered messages, but it does mean the server will not send any more messages for this consumer.

cancel_by_queue(queue)

Cancel consumer by queue name.

channel = None

The connection/channel to use for this consumer.

close()

End all active queue consumers.

Note

This does not affect already delivered messages, but it does mean the server will not send any more messages for this consumer.

property connection
consume(no_ack=None)

Start consuming messages.

Can be called multiple times, but note that while it will consume from new queues added since the last call, it will not cancel consuming from removed queues ( use cancel_by_queue()).

Parameters:

no_ack (bool) – See no_ack.

consuming_from(queue)

Return True if currently consuming from queue’.

declare()

Declare queues, exchanges and bindings.

Note

This is done automatically at instantiation when auto_declare is set.

flow(active)

Enable/disable flow from peer.

This is a simple flow-control mechanism that a peer can use to avoid overflowing its queues or otherwise finding itself receiving more messages than it can process.

The peer that receives a request to stop sending content will finish sending the current content (if any), and then wait until flow is reactivated.

no_ack = None

Flag for automatic message acknowledgment. If enabled the messages are automatically acknowledged by the broker. This can increase performance but means that you have no control of when the message is removed.

Disabled by default.

on_decode_error = None

Callback called when a message can’t be decoded.

The signature of the callback must take two arguments: (message, exc), which is the message that can’t be decoded and the exception that occurred while trying to decode it.

on_message = None

Optional function called whenever a message is received.

When defined this function will be called instead of the receive() method, and callbacks will be disabled.

So this can be used as an alternative to callbacks when you don’t want the body to be automatically decoded. Note that the message will still be decompressed if the message has the compression header set.

The signature of the callback must take a single argument, which is the Message object.

Also note that the message.body attribute, which is the raw contents of the message body, may in some cases be a read-only buffer object.

prefetch_count = None

Initial prefetch count

If set, the consumer will set the prefetch_count QoS value at startup. Can also be changed using qos().

purge()

Purge messages from all queues.

Warning

This will delete all ready messages, there is no undo operation.

qos(prefetch_size=0, prefetch_count=0, apply_global=False)

Specify quality of service.

The client can request that messages should be sent in advance so that when the client finishes processing a message, the following message is already held locally, rather than needing to be sent down the channel. Prefetching gives a performance improvement.

The prefetch window is Ignored if the no_ack option is set.

Parameters:
  • prefetch_size (int) – Specify the prefetch window in octets. The server will send a message in advance if it is equal to or smaller in size than the available prefetch size (and also falls within other prefetch limits). May be set to zero, meaning “no specific limit”, although other prefetch limits may still apply.

  • prefetch_count (int) – Specify the prefetch window in terms of whole messages.

  • apply_global (bool) – Apply new settings globally on all channels.

property queues
receive(body, message)

Method called when a message is received.

This dispatches to the registered callbacks.

Parameters:
  • body (Any) – The decoded message body.

  • message (Message) – The message instance.

Raises:

NotImplementedError – If no consumer callbacks have been registered.

recover(requeue=False)

Redeliver unacknowledged messages.

Asks the broker to redeliver all unacknowledged messages on the specified channel.

Parameters:

requeue (bool) – By default the messages will be redelivered to the original recipient. With requeue set to true, the server will attempt to requeue the message, potentially then delivering it to an alternative subscriber.

register_callback(callback)

Register a new callback to be called when a message is received.

Note

The signature of the callback needs to accept two arguments: (body, message), which is the decoded message body and the Message instance.

revive(channel)

Revive consumer after connection loss.

cancel_for(task_id)
consume_from(task_id)
drain_events(timeout=None)
on_after_fork()
start(initial_task_id, no_ack=True, **kwargs)
stop()
as_uri(include_password=True)[source]

Return the backend as an URI, sanitizing the password or not.

property binding
delete_group(group_id)[source]
destination_for(task_id, request)[source]

Get the destination for result by task id.

Returns:

tuple of (reply_to, correlation_id).

Return type:

Tuple[str, str]

ensure_chords_allowed()[source]
get_task_meta(task_id, backlog_limit=1000)[source]

Get task meta from backend.

if always_retry_backend_operation is activated, in the event of a recoverable exception, then retry operation with an exponential backoff until a limit has been reached.

property oid
on_out_of_band_result(task_id, message)[source]
on_reply_declare(task_id)[source]
on_result_fulfilled(result)[source]
on_task_call(producer, task_id)[source]
persistent = False

Set to true if the backend is persistent by default.

poll(task_id, backlog_limit=1000)

Get task meta from backend.

if always_retry_backend_operation is activated, in the event of a recoverable exception, then retry operation with an exponential backoff until a limit has been reached.

reload_group_result(task_id)[source]

Reload group result, even if it has been previously fetched.

reload_task_result(task_id)[source]

Reload task result, even if it has been previously fetched.

restore_group(group_id, cache=True)[source]

Get the result for a group.

retry_policy = {'interval_max': 1, 'interval_start': 0, 'interval_step': 1, 'max_retries': 20}
revive(channel)[source]
save_group(group_id, result)[source]

Store the result of an executed group.

store_result(task_id, result, state, traceback=None, request=None, **kwargs)[source]

Send task return value and state.

supports_autoexpire = True

If true the backend must automatically expire results. The daily backend_cleanup periodic task won’t be triggered in this case.

supports_native_join = True

If true the backend must implement get_many().