This document is for Kombu's development version, which can be significantly different from previous releases. Get the stable docs here: 5.3.

Kombu - kombu

Messaging library for Python.

kombu.enable_insecure_serializers(choices=<object object>)[source]

Enable serializers that are considered to be unsafe.

Note:

Will enable pickle, yaml and msgpack by default, but you can also specify a list of serializers (by name or content type) to enable.

kombu.disable_insecure_serializers(allowed=<object object>)[source]

Disable untrusted serializers.

Will disable all serializers except json or you can specify a list of deserializers to allow.

Note:

Producers will still be able to serialize data in these formats, but consumers will not accept incoming data using the untrusted content types.

Connection

class kombu.Connection(hostname='localhost', userid=None, password=None, virtual_host=None, port=None, insist=False, ssl=False, transport=None, connect_timeout=5, transport_options=None, login_method=None, uri_prefix=None, heartbeat=0, failover_strategy='round-robin', alternates=None, **kwargs)[source]

A connection to the broker.

Example:

>>> Connection('amqp://guest:guest@localhost:5672//')
>>> Connection('amqp://foo;amqp://bar',
...            failover_strategy='round-robin')
>>> Connection('redis://', transport_options={
...     'visibility_timeout': 3000,
... })
>>> import ssl
>>> Connection('amqp://', login_method='EXTERNAL', ssl={
...    'ca_certs': '/etc/pki/tls/certs/something.crt',
...    'keyfile': '/etc/something/system.key',
...    'certfile': '/etc/something/system.cert',
...    'cert_reqs': ssl.CERT_REQUIRED,
... })

Note:

SSL currently only works with the py-amqp, qpid and redis transports. For other transports you can use stunnel.

Arguments:

URL (str, Sequence): Broker URL, or a list of URLs.

Keyword Arguments:

ssl (bool/dict): Use SSL to connect to the server.

Default is False. May not be supported by the specified transport.

transport (Transport): Default transport if not specified in the URL. connect_timeout (float): Timeout in seconds for connecting to the

server. May not be supported by the specified transport.

transport_options (Dict): A dict of additional connection arguments to

pass to alternate kombu channel implementations. Consult the transport documentation for available options.

heartbeat (float): Heartbeat interval in int/float seconds.

Note that if heartbeats are enabled then the heartbeat_check() method must be called regularly, around once per second.

Note:

The connection is established lazily when needed. If you need the connection to be established, then force it by calling connect():

>>> conn = Connection('amqp://')
>>> conn.connect()

and always remember to close the connection:

>>> conn.release()

These options have been replaced by the URL argument, but are still supported for backwards compatibility:

keyword hostname:

Host name/address. NOTE: You cannot specify both the URL argument and use the hostname keyword argument at the same time.

keyword userid:

Default user name if not provided in the URL.

keyword password:

Default password if not provided in the URL.

keyword virtual_host:

Default virtual host if not provided in the URL.

keyword port:

Default port if not provided in the URL.

Attributes

hostname = None
port = None
userid = None
password = None
virtual_host = '/'
ssl = None
login_method = None
failover_strategy = 'round-robin'

Strategy used to select new hosts when reconnecting after connection failure. One of “round-robin”, “shuffle” or any custom iterator constantly yielding new URLs to try.

connect_timeout = 5
heartbeat = None

Heartbeat value, currently only supported by the py-amqp transport.

default_channel

Default channel.

Created upon access and closed when the connection is closed.

Note:

Can be used for automatic channel handling when you only need one channel, and also it is the channel implicitly used if a connection is passed instead of a channel, to functions that require a channel.

connected

Return true if the connection has been established.

recoverable_connection_errors

Recoverable connection errors.

List of connection related exceptions that can be recovered from, but where the connection must be closed and re-established first.

recoverable_channel_errors

Recoverable channel errors.

List of channel related exceptions that can be automatically recovered from without re-establishing the connection.

connection_errors

List of exceptions that may be raised by the connection.

channel_errors

List of exceptions that may be raised by the channel.

transport
connection

The underlying connection object.

Warning:

This instance is transport specific, so do not depend on the interface of this object.

uri_prefix = None
declared_entities = None

The cache of declared entities is per connection, in case the server loses data.

cycle = None

Iterator returning the next broker URL to try in the event of connection failure (initialized by failover_strategy).

host

The host as a host name/port pair separated by colon.

manager

AMQP Management API.

Experimental manager that can be used to manage/monitor the broker instance.

Not available for all transports.

supports_heartbeats
is_evented

Methods

as_uri(include_password=False, mask='**', getfields=operator.itemgetter('port', 'userid', 'password', 'virtual_host', 'transport')) str[source]

Convert connection parameters to URL form.

connect()[source]

Establish connection to server immediately.

channel()[source]

Create and return a new channel.

drain_events(**kwargs)[source]

Wait for a single event from the server.

Arguments:

timeout (float): Timeout in seconds before we give up.

raises socket.timeout:

if the timeout is exceeded.:

release()[source]

Close the connection (if open).

autoretry(fun, channel=None, **ensure_options)[source]

Decorator for functions supporting a channel keyword argument.

The resulting callable will retry calling the function if it raises connection or channel related errors. The return value will be a tuple of (retval, last_created_channel).

If a channel is not provided, then one will be automatically acquired (remember to close it afterwards).

Example:

>>> channel = connection.channel()
>>> try:
...    ret, channel = connection.autoretry(
...         publish_messages, channel)
... finally:
...    channel.close()
ensure_connection(*args, **kwargs)[source]

Public interface of _ensure_connection for retro-compatibility.

Returns kombu.Connection instance.

ensure(obj, fun, errback=None, max_retries=None, interval_start=1, interval_step=1, interval_max=1, on_revive=None, retry_errors=None)[source]

Ensure operation completes.

Regardless of any channel/connection errors occurring.

Retries by establishing the connection, and reapplying the function.

Arguments:

obj: The object to ensure an action on. fun (Callable): Method to apply.

errback (Callable): Optional callback called each time the

connection can’t be established. Arguments provided are the exception raised and the interval that will be slept (exc, interval).

max_retries (int): Maximum number of times to retry.

If this limit is exceeded the connection error will be re-raised.

interval_start (float): The number of seconds we start

sleeping for.

interval_step (float): How many seconds added to the interval

for each retry.

interval_max (float): Maximum number of seconds to sleep between

each retry.

on_revive (Callable): Optional callback called whenever

revival completes successfully

retry_errors (tuple): Optional list of errors to retry on

regardless of the connection state.

Examples

>>> from kombu import Connection, Producer
>>> conn = Connection('amqp://')
>>> producer = Producer(conn)
>>> def errback(exc, interval):
...     logger.error('Error: %r', exc, exc_info=1)
...     logger.info('Retry in %s seconds.', interval)
>>> publish = conn.ensure(producer, producer.publish,
...                       errback=errback, max_retries=3)
>>> publish({'hello': 'world'}, routing_key='dest')
revive(new_channel)[source]

Revive connection after connection re-established.

create_transport()[source]
get_transport_cls()[source]

Get the currently used transport class.

clone(**kwargs)[source]

Create a copy of the connection with same settings.

info()[source]

Get connection info.

switch(conn_str)[source]

Switch connection parameters to use a new URL or hostname.

Note:

Does not reconnect!

Arguments:

conn_str (str): either a hostname or URL.

maybe_switch_next()[source]

Switch to next URL given by the current failover strategy.

heartbeat_check(rate=2)[source]

Check heartbeats.

Allow the transport to perform any periodic tasks required to make heartbeats work. This should be called approximately every second.

If the current transport does not support heartbeats then this is a noop operation.

Arguments:

rate (int): Rate is how often the tick is called

compared to the actual heartbeat value. E.g. if the heartbeat is set to 3 seconds, and the tick is called every 3 / 2 seconds, then the rate is 2. This value is currently unused by any transports.

maybe_close_channel(channel)[source]

Close given channel, but ignore connection and channel errors.

register_with_event_loop(loop)[source]
close()

Close the connection (if open).

_close()[source]

Really close connection, even if part of a connection pool.

completes_cycle(retries)[source]

Return true if the cycle is complete after number of retries.

get_manager(*args, **kwargs)[source]
Producer(channel=None, *args, **kwargs)[source]

Create new kombu.Producer instance.

Consumer(queues=None, channel=None, *args, **kwargs)[source]

Create new kombu.Consumer instance.

Pool(limit=None, **kwargs)[source]

Pool of connections.

Arguments:

limit (int): Maximum number of active connections.

Default is no limit.

Example:

>>> connection = Connection('amqp://')
>>> pool = connection.Pool(2)
>>> c1 = pool.acquire()
>>> c2 = pool.acquire()
>>> c3 = pool.acquire()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "kombu/connection.py", line 354, in acquire
  raise ConnectionLimitExceeded(self.limit)
    kombu.exceptions.ConnectionLimitExceeded: 2
>>> c1.release()
>>> c3 = pool.acquire()
ChannelPool(limit=None, **kwargs)[source]

Pool of channels.

Arguments:

limit (int): Maximum number of active channels.

Default is no limit.

Example:

>>> connection = Connection('amqp://')
>>> pool = connection.ChannelPool(2)
>>> c1 = pool.acquire()
>>> c2 = pool.acquire()
>>> c3 = pool.acquire()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "kombu/connection.py", line 354, in acquire
  raise ChannelLimitExceeded(self.limit)
    kombu.connection.ChannelLimitExceeded: 2
>>> c1.release()
>>> c3 = pool.acquire()
SimpleQueue(name, no_ack=None, queue_opts=None, queue_args=None, exchange_opts=None, channel=None, **kwargs)[source]

Simple persistent queue API.

Create new SimpleQueue, using a channel from this connection.

If name is a string, a queue and exchange will be automatically created using that name as the name of the queue and exchange, also it will be used as the default routing key.

Arguments:

name (str, kombu.Queue): Name of the queue/or a queue. no_ack (bool): Disable acknowledgments. Default is false. queue_opts (Dict): Additional keyword arguments passed to the

constructor of the automatically created Queue.

queue_args (Dict): Additional keyword arguments passed to the

constructor of the automatically created Queue for setting implementation extensions (e.g., in RabbitMQ).

exchange_opts (Dict): Additional keyword arguments passed to the

constructor of the automatically created Exchange.

channel (ChannelT): Custom channel to use. If not specified the

connection default channel is used.

SimpleBuffer(name, no_ack=None, queue_opts=None, queue_args=None, exchange_opts=None, channel=None, **kwargs)[source]

Simple ephemeral queue API.

Create new SimpleQueue using a channel from this connection.

Exchange

Example creating an exchange declaration:

>>> news_exchange = Exchange('news', type='topic')

For now news_exchange is just a declaration, you can’t perform actions on it. It just describes the name and options for the exchange.

The exchange can be bound or unbound. Bound means the exchange is associated with a channel and operations can be performed on it. To bind the exchange you call the exchange with the channel as argument:

>>> bound_exchange = news_exchange(channel)

Now you can perform operations like declare() or delete():

>>> # Declare exchange manually
>>> bound_exchange.declare()

>>> # Publish raw string message using low-level exchange API
>>> bound_exchange.publish(
...     'Cure for cancer found!',
...     routing_key='news.science',
... )

>>> # Delete exchange.
>>> bound_exchange.delete()
class kombu.Exchange(name='', type='', channel=None, **kwargs)[source]

An Exchange declaration.

Arguments:

name (str): See name. type (str): See type. channel (kombu.Connection, ChannelT): See channel. durable (bool): See durable. auto_delete (bool): See auto_delete. delivery_mode (enum): See delivery_mode. arguments (Dict): See arguments. no_declare (bool): See no_declare

name(str)

Default is no name (the default exchange).

Type:

Name of the exchange.

type(str)

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.

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

durable (bool): Durable exchanges remain active when a server restarts.

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

auto_delete (bool): If set, the exchange is deleted when all queues

have finished using it. Default is False.

delivery_mode (enum): 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).

arguments (Dict): Additional arguments to specify when the exchange

is declared.

no_declare (bool): Never declare this exchange

(declare() does nothing).

maybe_bind(channel: Channel | Connection) _MaybeChannelBoundType

Bind instance to channel if not already bound.

Message(body, delivery_mode=None, properties=None, **kwargs)[source]

Create message instance to be sent with publish().

Arguments:

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: tuple[tuple[str, Any], ...] = (('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)[source]

Bind the exchange to another exchange.

Arguments:

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)[source]
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)[source]

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)[source]

Delete the exchange declaration on server.

Arguments:

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)[source]

Publish message.

Arguments:

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)[source]

Delete previously created exchange binding from the server.

Queue

Example creating a queue using our exchange in the Exchange example:

>>> science_news = Queue('science_news',
...                      exchange=news_exchange,
...                      routing_key='news.science')

For now science_news is just a declaration, you can’t perform actions on it. It just describes the name and options for the queue.

The queue can be bound or unbound. Bound means the queue is associated with a channel and operations can be performed on it. To bind the queue you call the queue instance with the channel as an argument:

>>> bound_science_news = science_news(channel)

Now you can perform operations like declare() or purge():

>>> bound_science_news.declare()
>>> bound_science_news.purge()
>>> bound_science_news.delete()
class kombu.Queue(name='', exchange=None, routing_key='', channel=None, bindings=None, on_declared=None, **kwargs)[source]

A Queue declaration.

Arguments:

name (str): See name. exchange (Exchange, str): See exchange. routing_key (str): See routing_key. channel (kombu.Connection, ChannelT): See channel. durable (bool): See durable. exclusive (bool): See exclusive. auto_delete (bool): See auto_delete. queue_arguments (Dict): See queue_arguments. binding_arguments (Dict): See binding_arguments. consumer_arguments (Dict): See consumer_arguments. no_declare (bool): See no_declare. on_declared (Callable): See on_declared. expires (float): See expires. message_ttl (float): See message_ttl. max_length (int): See max_length. max_length_bytes (int): See max_length_bytes. max_priority (int): See max_priority.

name(str)

Default is no name (default queue destination).

Type:

Name of the queue.

exchange(Exchange)
Type:

The Exchange the queue binds to.

routing_key(str)

The interpretation of the routing key depends on the Exchange.type.

  • direct exchange

    Matches if the routing key property of the message and the routing_key attribute are identical.

  • fanout exchange

    Always matches, even if the binding does not have a key.

  • topic exchange

    Matches the routing key property of the message by a primitive pattern matching scheme. The message routing key then consists of words separated by dots (“.”, like domain names), and two special characters are available; star (“*”) and hash (“#”). The star matches any word, and the hash matches zero or more words. For example “*.stock.#” matches the routing keys “usd.stock” and “eur.stock.db” but not “stock.nasdaq”.

Type:

The routing key (if any), also called binding key.

channel(ChannelT)
Type:

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

durable(bool)

Non-durable queues (transient queues) are purged if/when a server restarts. Note that durable queues do not necessarily hold persistent messages, although it does not make sense to send persistent messages to a transient queue.

Default is True.

Type:

Durable queues remain active when a server restarts.

exclusive(bool)

current connection. Setting the ‘exclusive’ flag always implies ‘auto-delete’.

Default is False.

Type:

Exclusive queues may only be consumed from by the

auto_delete(bool)

have finished using it. Last consumer can be canceled either explicitly or because its channel is closed. If there was no consumer ever on the queue, it won’t be deleted.

Type:

If set, the queue is deleted when all consumers

expires(float)

queue should expire.

The expiry time decides how long the queue can stay unused before it’s automatically deleted. Unused means the queue has no consumers, the queue has not been redeclared, and Queue.get has not been invoked for a duration of at least the expiration period.

See https://www.rabbitmq.com/ttl.html#queue-ttl

RabbitMQ extension: Only available when using RabbitMQ.

Type:

Set the expiry time (in seconds) for when this

message_ttl(float)

This setting controls how long messages can stay in the queue unconsumed. If the expiry time passes before a message consumer has received the message, the message is deleted and no consumer will see the message.

See https://www.rabbitmq.com/ttl.html#per-queue-message-ttl

RabbitMQ extension: Only available when using RabbitMQ.

Type:

Message time to live in seconds.

max_length(int)

queue can hold.

If the number of messages in the queue size exceeds this limit, new messages will be dropped (or dead-lettered if a dead letter exchange is active).

See https://www.rabbitmq.com/maxlength.html

RabbitMQ extension: Only available when using RabbitMQ.

Type:

Set the maximum number of messages that the

max_length_bytes(int)

of messages in the queue.

If the total size of all the messages in the queue exceeds this limit, new messages will be dropped (or dead-lettered if a dead letter exchange is active).

RabbitMQ extension: Only available when using RabbitMQ.

Type:

Set the max size (in bytes) for the total

max_priority(int)

For example if the value is 10, then messages can delivered to this queue can have a priority value between 0 and 10, where 10 is the highest priority.

RabbitMQ queues without a max priority set will ignore the priority field in the message, so if you want priorities you need to set the max priority field to declare the queue as a priority queue.

RabbitMQ extension: Only available when using RabbitMQ.

Type:

Set the highest priority number for this queue.

queue_arguments(Dict)

the queue. Can be used to to set the arguments value for RabbitMQ/AMQP’s queue.declare.

Type:

Additional arguments used when declaring

binding_arguments(Dict)

the queue. Can be used to to set the arguments value for RabbitMQ/AMQP’s queue.declare.

Type:

Additional arguments used when binding

consumer_arguments(Dict)

from this queue. Can be used to to set the arguments value for RabbitMQ/AMQP’s basic.consume.

Type:

Additional arguments used when consuming

alias(str)

of this, for example to give alternate names to queues with automatically generated queue names.

Type:

Unused in Kombu, but applications can take advantage

on_declared(Callable)

queue has been declared (the queue_declare operation is complete). This must be a function with a signature that accepts at least 3 positional arguments: (name, messages, consumers).

Type:

Optional callback to be applied when the

no_declare(bool)

entities (declare() does nothing).

Type:

Never declare this queue, nor related

maybe_bind(channel: Channel | Connection) _MaybeChannelBoundType

Bind instance to channel if not already bound.

exception ContentDisallowed

Consumer does not allow this content-type.

as_dict(recurse=False)[source]
attrs: tuple[tuple[str, Any], ...] = (('name', None), ('exchange', None), ('routing_key', None), ('queue_arguments', None), ('binding_arguments', None), ('consumer_arguments', None), ('durable', <class 'bool'>), ('exclusive', <class 'bool'>), ('auto_delete', <class 'bool'>), ('no_ack', None), ('alias', None), ('bindings', <class 'list'>), ('no_declare', <class 'bool'>), ('expires', <class 'float'>), ('message_ttl', <class 'float'>), ('max_length', <class 'int'>), ('max_length_bytes', <class 'int'>), ('max_priority', <class 'int'>))
auto_delete = False
bind(channel)[source]

Create copy of the instance that is bound to a channel.

bind_to(exchange='', routing_key='', arguments=None, nowait=False, channel=None)[source]
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.

cancel(consumer_tag)[source]

Cancel a consumer by consumer tag.

consume(consumer_tag='', callback=None, no_ack=None, nowait=False, on_cancel=None)[source]

Start a queue consumer.

Consumers last as long as the channel they were created on, or until the client cancels them.

Arguments:

consumer_tag (str): Unique identifier for the consumer.

The consumer tag is local to a connection, so two clients can use the same consumer tags. If this field is empty the server will generate a unique tag.

no_ack (bool): If enabled the broker will automatically

ack messages.

nowait (bool): Do not wait for a reply.

callback (Callable): callback called for each delivered message.

on_cancel (Callable): callback called on cancel notify received

from broker.

declare(nowait=False, channel=None)[source]

Declare queue and exchange then binds queue to exchange.

delete(if_unused=False, if_empty=False, nowait=False)[source]

Delete the queue.

Arguments:

if_unused (bool): If set, the server will only delete the queue

if it has no consumers. A channel error will be raised if the queue has consumers.

if_empty (bool): If set, the server will only delete the queue if

it is empty. If it is not empty a channel error will be raised.

nowait (bool): Do not wait for a reply.

durable = True
exchange = <unbound Exchange ''(direct)>
exclusive = False
classmethod from_dict(queue, **options)[source]
get(no_ack=None, accept=None)[source]

Poll the server for a new message.

This method provides direct access to the messages in a queue using a synchronous dialogue, designed for specific types of applications where synchronous functionality is more important than performance.

Returns:

~kombu.Message – or None otherwise.

Return type:

if a message was available,

Arguments:

no_ack (bool): If enabled the broker will

automatically ack messages.

accept (Set[str]): Custom list of accepted content types.

name = ''
no_ack = False
purge(nowait=False)[source]

Remove all ready messages from the queue.

queue_bind(nowait=False, channel=None)[source]

Create the queue binding on the server.

queue_declare(nowait=False, passive=False, channel=None)[source]

Declare queue on the server.

Arguments:

nowait (bool): Do not wait for a reply. passive (bool): If set, the server will not create the queue.

The client can use this to check whether a queue exists without modifying the server state.

queue_unbind(arguments=None, nowait=False, channel=None)[source]
routing_key = ''
unbind_from(exchange='', routing_key='', arguments=None, nowait=False, channel=None)[source]

Unbind queue by deleting the binding from the server.

when_bound()[source]

Callback called when the class is bound.

Message Producer

class kombu.Producer(channel, exchange=None, routing_key=None, serializer=None, auto_declare=None, compression=None, on_return=None)[source]

Message Producer.

Arguments:

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.

channel
exchange = None

Default exchange

routing_key = ''

Default routing key.

serializer = None

Default serializer to use. Default is JSON.

compression = None

Default compression method. Disabled by default.

auto_declare = True

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

on_return = None

Basic return callback.

connection
declare()[source]

Declare the exchange.

Note:

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

maybe_declare(entity, retry=False, **retry_policy)[source]

Declare exchange if not already declared during this session.

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)[source]

Publish message to the specified exchange.

Arguments:

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.

revive(channel)[source]

Revive the producer after connection loss.

Message Consumer

class kombu.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]

Message consumer.

Arguments:

channel (kombu.Connection, ChannelT): see channel. queues (Sequence[kombu.Queue]): see queues. no_ack (bool): see no_ack. auto_declare (bool): see auto_declare callbacks (Sequence[Callable]): see callbacks. on_message (Callable): See on_message on_decode_error (Callable): see on_decode_error. prefetch_count (int): see prefetch_count.

channel = None

The connection/channel to use for this consumer.

queues

A single Queue, or a list of queues to consume from.

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.

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.

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.

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.

connection
declare()[source]

Declare queues, exchanges and bindings.

Note:

This is done automatically at instantiation when auto_declare is set.

register_callback(callback)[source]

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.

add_queue(queue)[source]

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.

consume(no_ack=None)[source]

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()).

Arguments:

no_ack (bool): See no_ack.

cancel()[source]

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)[source]

Cancel consumer by queue name.

consuming_from(queue)[source]

Return True if currently consuming from queue’.

purge()[source]

Purge messages from all queues.

Warning:

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

flow(active)[source]

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.

qos(prefetch_size=0, prefetch_count=0, apply_global=False)[source]

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.

Arguments:

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.

recover(requeue=False)[source]

Redeliver unacknowledged messages.

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

Arguments:

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.

receive(body, message)[source]

Method called when a message is received.

This dispatches to the registered callbacks.

Arguments:

body (Any): The decoded message body. message (~kombu.Message): The message instance.

raises NotImplementedError:

If no consumer callbacks have been: registered.

revive(channel)[source]

Revive consumer after connection loss.