Skip to content

Channel

channel

The Channel class provides a wrapper for interacting with RabbitMQ implementing the methods and behaviors for an AMQP Channel.

Channel

A Channel is the primary communication method for interacting with RabbitMQ.

It is recommended that you do not directly invoke the creation of a channel object in your application code but rather construct a channel by calling the active connection's channel() method.

Source code in pika/channel.py
class Channel:
    """
    A Channel is the primary communication method for interacting with RabbitMQ.

    It is recommended that you do not directly invoke the creation of a channel object in your
    application code but rather construct a channel by calling the active connection's channel()
    method.
    """

    CLOSED = 0
    OPENING = 1
    OPEN = 2
    CLOSING = 3  # client-initiated close in progress

    _STATE_NAMES: ClassVar[dict[int, str]] = {
        CLOSED: 'CLOSED',
        OPENING: 'OPENING',
        OPEN: 'OPEN',
        CLOSING: 'CLOSING'
    }

    _ON_CHANNEL_CLEANUP_CB_KEY = '_on_channel_cleanup'

    # Upper bound on the number of nowait-cancelled consumer tags retained in
    # `_cancelled`; see `_retain_cancelled_tag`.
    _MAX_RETAINED_CANCELLED_TAGS = 1024

    def __init__(self, connection: Connection, channel_number: int,
                 on_open_callback: _OnOpenCallback | None) -> None:
        """
        Create a new instance of the Channel.

        :param connection: The connection
        :param channel_number: The channel number for this instance
        :param on_open_callback: The callback to call on channel open. The callback will be invoked
            with the `Channel` instance as its only argument.
        """
        if not isinstance(channel_number, int):
            raise exceptions.InvalidChannelNumber(channel_number)

        validators.rpc_completion_callback(on_open_callback)

        self.channel_number = channel_number
        self.callbacks = connection.callbacks
        self.connection = connection

        # Initially, flow is assumed to be active
        self.flow_active = True

        self._content_assembler = ContentFrameAssembler()

        self._blocked: deque = deque()
        self._blocking: Any | None = None
        self._has_on_flow_callback: bool = False
        self._cancelled: set = set()
        # Nowait-cancelled tags in cancellation order, bounding how many of
        # them `_cancelled` retains; see `_retain_cancelled_tag`.
        self._nowait_cancelled: deque = deque()
        self._consumers: dict = {}
        self._consumers_with_noack: set = set()
        self._on_flowok_callback: Callable[..., Any] | None = None
        self._on_getok_callback: Callable[..., Any] | None = None
        self._on_ack_nack_callback: _OnAckNackCallback | None = None
        self._on_openok_callback: Callable[..., Any] | None = on_open_callback
        self._state: int = self.CLOSED

        # We save the closing reason exception to be passed to on-channel-close
        # callback at closing of the channel. Exception representing the closing
        # reason; ChannelClosedByClient or ChannelClosedByBroker on controlled
        # close; otherwise another exception describing the reason for failure
        # (most likely connection failure).
        self._closing_reason = None  # type: None | Exception

        # opaque cookie value set by wrapper layer (e.g., BlockingConnection)
        # via _set_cookie
        self._cookie: object = None

    def __int__(self) -> int:
        """Return the channel object as its channel number."""
        return self.channel_number

    @override
    def __repr__(self) -> str:
        return f'<{self.__class__.__name__} number={self.channel_number} {self._STATE_NAMES[self._state]} conn={self.connection!r}>'

    def add_callback(self,
                     callback: Callable[..., Any],
                     replies: Sequence[type[amqp_object.Method]],
                     one_shot: bool = True) -> None:
        """
        Pass in a callback handler and a list replies from the RabbitMQ broker which you'd like the
        callback notified of. Callbacks should allow for the frame parameter to be passed in.

        :param callback: The callback to call
        :param replies: The replies to get a callback for
        :param one_shot: Only handle the first type callback
        """
        for reply in replies:
            self.callbacks.add(self.channel_number, reply, callback, one_shot)

    def add_on_cancel_callback(self, callback: _OnCancelCallback) -> None:
        """
        Pass a callback function that will be called when the basic_cancel is sent by the server.
        The callback function should receive a frame parameter.

        :param callback: The callback to call on Basic.Cancel from broker
        """
        self.callbacks.add(self.channel_number, spec.Basic.Cancel, callback,
                           False)

    def add_on_close_callback(self, callback: _OnCloseCallback) -> None:
        """
        Pass a callback function that will be called when the channel is closed.

        The callback function will receive the channel and an exception describing why the channel
        was closed.

        If the channel is closed by broker via Channel.Close, the callback will receive
        `ChannelClosedByBroker` as the reason.

        If graceful user-initiated channel closing completes successfully ( either directly of
        indirectly by closing a connection containing the channel) and closing concludes gracefully
        without Channel.Close from the broker and without loss of connection, the callback will
        receive `ChannelClosedByClient` exception as reason.

        If channel was closed due to loss of connection, the callback will receive another exception
        type describing the failure.

        :param callback: The callback, having the signature: callback(Channel, Exception reason)
        """
        self.callbacks.add(self.channel_number, '_on_channel_close', callback,
                           False, self)

    def add_on_flow_callback(self, callback: _OnFlowCallback) -> None:
        """
        Pass a callback function that will be called when Channel.Flow is called by the remote
        server. Note that newer versions of RabbitMQ will not issue this but instead use TCP
        backpressure.

        :param callback: The callback function
        """
        self._has_on_flow_callback = True
        self.callbacks.add(self.channel_number, spec.Channel.Flow, callback,
                           False)

    def add_on_return_callback(self, callback: _OnReturnCallback) -> None:
        """
        Pass a callback function that will be called when basic_publish is sent a message that has
        been rejected and returned by the server.

        :param callback: The function to call, having the signature
                                callback(channel, method, properties, body)
                                where
                                - channel: pika.channel.Channel
                                - method: pika.spec.Basic.Return
                                - properties: pika.spec.BasicProperties
                                - body: bytes
        """
        self.callbacks.add(self.channel_number, '_on_return', callback, False)

    def remove_callback(
            self,
            callback: Callable[..., Any],
            replies: Sequence[type[amqp_object.Method]] | None = None) -> bool:
        """
        Remove a callback previously registered via :meth:`add_callback`.

        Mirrors :meth:`add_callback`: the callback is matched by identity and removed
        from each reply key it is registered under. If ``replies`` is ``None``, the
        callback is removed from every reply key it is currently registered under.

        :param callback: The callback to remove
        :param replies: The replies to remove the callback from, or ``None`` to
            remove it from every reply key it is registered under
        :returns: ``True`` if at least one matching callback was removed
        """
        reply_keys = (self.callbacks.keys(self.channel_number)
                      if replies is None else replies)
        removed = False
        for reply in reply_keys:
            if self.callbacks.remove_matching(self.channel_number, reply,
                                              lambda cb: cb == callback):
                removed = True
        return removed

    def remove_on_cancel_callback(self, callback: _OnCancelCallback) -> bool:
        """
        Remove a callback registered via :meth:`add_on_cancel_callback`.

        :param callback: The callback to remove
        :returns:``True`` if the callback was removed, ``False`` if it was absent
        """
        return self.callbacks.remove_matching(self.channel_number,
                                              spec.Basic.Cancel,
                                              lambda cb: cb == callback)

    def remove_on_close_callback(self, callback: _OnCloseCallback) -> bool:
        """
        Remove a callback registered via :meth:`add_on_close_callback`.

        :param callback: The callback to remove
        :returns:``True`` if the callback was removed, ``False`` if it was absent
        """
        return self.callbacks.remove_matching(self.channel_number,
                                              '_on_channel_close',
                                              lambda cb: cb == callback)

    def remove_on_flow_callback(self, callback: _OnFlowCallback) -> bool:
        """
        Remove a callback registered via :meth:`add_on_flow_callback`.

        :param callback: The callback to remove
        :returns:``True`` if the callback was removed, ``False`` if it was absent
        """
        return self.callbacks.remove_matching(self.channel_number,
                                              spec.Channel.Flow,
                                              lambda cb: cb == callback)

    def remove_on_return_callback(self, callback: _OnReturnCallback) -> bool:
        """
        Remove a callback registered via :meth:`add_on_return_callback`.

        :param callback: The callback to remove
        :returns:``True`` if the callback was removed, ``False`` if it was absent
        """
        return self.callbacks.remove_matching(self.channel_number, '_on_return',
                                              lambda cb: cb == callback)

    def basic_ack(self, delivery_tag: int = 0, multiple: bool = False) -> None:
        """
        Acknowledge one or more messages.

        When sent by the client, this method acknowledges one or more messages delivered via the
        Deliver or Get-Ok methods. When sent by server, this method acknowledges one or more
        messages published with the Publish method on a channel in confirm mode. The acknowledgement
        can be for a single message or a set of messages up to and including a specific message.

        :param delivery_tag: int/long The server-assigned delivery tag
        :param multiple: If set to True, the delivery tag is treated as "up to and including", so
            that multiple messages can be acknowledged with a single method. If set to False, the
            delivery tag refers to a single message. If the multiple field is 1, and the delivery
            tag is zero, this indicates acknowledgement of all outstanding messages.
        """
        self._raise_if_not_open()
        return self._send_method(spec.Basic.Ack(delivery_tag, multiple))

    def basic_cancel(self,
                     consumer_tag: str = '',
                     callback: _OnBasicCancelCallback | None = None) -> None:
        """
        This method cancels a consumer.

        This does not affect already delivered messages, but it does mean the server will not send
        any more messages for that consumer. The client may receive an arbitrary number of messages
        in between sending the cancel method and receiving the cancel-ok reply. It may also be sent
        from the server to the client in the event of the consumer being unexpectedly cancelled
        (i.e. cancelled for any reason other than the server receiving the corresponding
        basic.cancel from the client). This allows clients to be notified of the loss of consumers
        due to events such as queue deletion.

        A cancelled consumer's tag is retained so that a delivery already in flight when the cancel
        was sent is rejected rather than left unacknowledged. A cancel that expects a Basic.CancelOk
        retires its own entry on arrival; a nowait cancel has no reply to retire it, so its tag is
        kept only until `_MAX_RETAINED_CANCELLED_TAGS` later nowait cancels displace it (see
        `_retain_cancelled_tag`). Past that point its retention lapses: a straggling delivery for it
        is logged as unexpected and left unacknowledged rather than rejected, and the tag may be
        reused by `basic_consume`, so reusing the same explicit consumer_tag risks a delivery for
        the old consumer reaching the new one. The cap is a generous approximation of the broker's
        in-flight window, so this only bites under extreme nowait-cancel churn.

        :param consumer_tag: Identifier for the consumer
        :param callback: callback(pika.frame.Method) for method Basic.CancelOk. If None, do not
            expect a Basic.CancelOk response, otherwise, callback must be callable
        :raises ValueError:
        """
        validators.require_string(consumer_tag, 'consumer_tag')
        self._raise_if_not_open()
        nowait = validators.rpc_completion_callback(callback)

        if consumer_tag in self._cancelled:
            # We check for cancelled first, because basic_cancel removes
            # consumers closed with nowait from self._consumers
            LOGGER.warning('basic_cancel - consumer is already cancelling: %s',
                           consumer_tag)
            return

        if consumer_tag not in self._consumers:
            # Could be cancelled by user or broker earlier
            LOGGER.warning('basic_cancel - consumer not found: %s',
                           consumer_tag)
            return

        LOGGER.debug('Cancelling consumer: %s (nowait=%s)', consumer_tag,
                     nowait)

        if nowait:
            # This is our last opportunity while the channel is open to remove
            # this consumer callback and help gc.
            del self._consumers[consumer_tag]

        if callback is not None:
            self.callbacks.add(self.channel_number, spec.Basic.CancelOk,
                               callback)

        self._cancelled.add(consumer_tag)

        if nowait:
            self._retain_cancelled_tag(consumer_tag)

        self._rpc(spec.Basic.Cancel(consumer_tag=consumer_tag, nowait=nowait),
                  self._on_cancelok if not nowait else None,
                  [(spec.Basic.CancelOk, {
                      'consumer_tag': consumer_tag
                  })] if not nowait else [])

    def basic_consume(self,
                      queue: str,
                      on_message_callback: _OnMessageCallback,
                      auto_ack: bool = False,
                      exclusive: bool = False,
                      consumer_tag: str | None = None,
                      arguments: dict[str, Any] | None = None,
                      callback: _OnBasicConsumeCallback | None = None) -> str:
        """
        Sends the AMQP 0-9-1 command Basic.Consume to the broker and binds messages for the
        consumer_tag to the consumer callback. If you do not pass in a consumer_tag, one will be
        automatically generated for you. Returns the consumer tag.

        For more information on basic_consume, see:
        Tutorial 2 at https://www.rabbitmq.com/getstarted.html
        https://www.rabbitmq.com/confirms.html
        https://www.rabbitmq.com/amqp-0-9-1-reference.html#basic.consume

        :param queue: The queue to consume from. Use the empty string to
            specify the most recent server-named queue for this channel
        :param on_message_callback: The function to call when
            consuming with the signature
            on_message_callback(channel, method, properties, body), where
            - channel: pika.channel.Channel
            - method: pika.spec.Basic.Deliver
            - properties: pika.spec.BasicProperties
            - body: bytes
        :param auto_ack: if set to True, automatic acknowledgement mode
            will be used (see https://www.rabbitmq.com/confirms.html).
            This corresponds with the 'no_ack' parameter in the basic.consume
            AMQP 0.9.1 method
        :param exclusive: Don't allow other consumers on the queue
        :param consumer_tag: Specify your own consumer tag
        :param arguments: Custom key/value pair arguments for the consumer
        :param callback: callback(pika.frame.Method) for method
          Basic.ConsumeOk.
        :returns: Consumer tag which may be used to cancel the consumer.
        :raises ValueError:
        """
        validators.require_string(queue, 'queue')
        validators.require_callback(on_message_callback)
        self._raise_if_not_open()
        validators.rpc_completion_callback(callback)

        # If a consumer tag was not passed, create one
        if not consumer_tag:
            consumer_tag = self._generate_consumer_tag()

        if consumer_tag in self._consumers or consumer_tag in self._cancelled:
            raise exceptions.DuplicateConsumerTag(consumer_tag)

        if auto_ack:
            self._consumers_with_noack.add(consumer_tag)

        self._consumers[consumer_tag] = on_message_callback

        rpc_callback: Callable[
            ...,
            Any] | None = self._on_eventok if callback is None else callback

        self._rpc(
            spec.Basic.Consume(queue=queue,
                               consumer_tag=consumer_tag,
                               no_ack=auto_ack,
                               exclusive=exclusive,
                               arguments=arguments or {}), rpc_callback,
            [(spec.Basic.ConsumeOk, {
                'consumer_tag': consumer_tag
            })])

        return consumer_tag

    def _generate_consumer_tag(self) -> str:
        """
        Generate a consumer tag.

        NOTE: this protected method may be called by derived classes

        :returns: consumer tag
        """
        return f'ctag{self.channel_number}.{uuid.uuid4().hex}'

    def basic_get(self,
                  queue: str,
                  callback: _OnBasicGetCallback,
                  auto_ack: bool = False) -> None:
        """
        Get a single message from the AMQP broker.

        If you want to be notified of Basic.GetEmpty, use the Channel.add_callback method
        adding your Basic.GetEmpty callback which should expect only one
        parameter, frame. Due to implementation details, this cannot be called
        a second time until the callback is executed.  For more information on
        basic_get and its parameters, see:

        https://www.rabbitmq.com/amqp-0-9-1-reference.html#basic.get

        :param queue: The queue from which to get a message. Use the empty
            string to specify the most recent server-named queue for this
            channel
        :param callback: The callback to call with a message that has
            the signature callback(channel, method, properties, body), where:
            - channel: pika.channel.Channel
            - method: pika.spec.Basic.GetOk
            - properties: pika.spec.BasicProperties
            - body: bytes
        :param auto_ack: Tell the broker to not expect a reply
        :raises ValueError:
        """
        validators.require_string(queue, 'queue')
        validators.require_callback(callback)
        if self._on_getok_callback is not None:
            raise exceptions.DuplicateGetOkCallback()
        self._on_getok_callback = callback

        # TODO Strangely, not using _rpc for the synchronous Basic.Get. Would
        # need to extend _rpc to handle Basic.GetOk method, header, and body
        # frames (or similar)
        self._send_method(spec.Basic.Get(queue=queue, no_ack=auto_ack))

    def basic_nack(self,
                   delivery_tag: int = 0,
                   multiple: bool = False,
                   requeue: bool = True) -> None:
        """
        This method allows a client to reject one or more incoming messages.

        It can be used to interrupt and cancel large incoming messages, or return untreatable
        messages to their original queue.

        :param delivery_tag: int/long The server-assigned delivery tag
        :param multiple: If set to True, the delivery tag is treated as "up to and including", so
            that multiple messages can be acknowledged with a single method. If set to False, the
            delivery tag refers to a single message. If the multiple field is 1, and the delivery
            tag is zero, this indicates acknowledgement of all outstanding messages.
        :param requeue: If requeue is true, the server will attempt to requeue the message. If
            requeue is false or the requeue attempt fails the messages are discarded or dead-
            lettered.
        """
        self._raise_if_not_open()
        return self._send_method(
            spec.Basic.Nack(delivery_tag, multiple, requeue))

    def basic_publish(self,
                      exchange: str,
                      routing_key: str,
                      body: bytes,
                      properties: spec.BasicProperties | None = None,
                      mandatory: bool = False) -> None:
        """
        Publish to the channel with the given exchange, routing key and body.

        For more information on basic_publish and what the parameters do, see:

        https://www.rabbitmq.com/amqp-0-9-1-reference.html#basic.publish

        :param exchange: The exchange to publish to
        :param routing_key: The routing key to bind on
        :param body: The message body
        :param properties: Basic.properties
        :param mandatory: The mandatory flag
        """
        self._raise_if_not_open()
        body = as_bytes(body)
        properties = properties or spec.BasicProperties()
        self._send_method(
            spec.Basic.Publish(exchange=exchange,
                               routing_key=routing_key,
                               mandatory=mandatory), (properties, body))

    def basic_qos(self,
                  prefetch_size: int = 0,
                  prefetch_count: int = 0,
                  global_qos: bool = False,
                  callback: _OnBasicQosCallback | None = None) -> None:
        """
        Specify quality of service.

        This method requests a specific quality of service. The client can request that messages 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. The QoS can be
        applied separately to each new consumer on channel or shared across all consumers on the
        channel. Prefetching gives a performance improvement.

        :param prefetch_size: This field specifies the prefetch window size. 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 into other prefetch limits). May be set to zero, meaning "no specific
            limit", although other prefetch limits may still apply. The prefetch-size is ignored by
            consumers who have enabled the no-ack option.
        :param prefetch_count: Specifies a prefetch window in terms of whole messages. This field
            may be used in combination with the prefetch-size field; a message will only be sent in
            advance if both prefetch windows (and those at the channel and connection level) allow
            it. The prefetch-count is ignored by consumers who have enabled the no-ack option.
        :param global_qos: Should the QoS be shared across all consumers on the channel.
        :param callback: The callback to call for Basic.QosOk response
        :returns:``None``. Method frame from the Basic.Qos-ok response is delivered to ``callback``
            when provided.
        :raises ValueError:
        """
        self._raise_if_not_open()
        validators.rpc_completion_callback(callback)
        validators.zero_or_greater('prefetch_size', prefetch_size)
        validators.zero_or_greater('prefetch_count', prefetch_count)
        return self._rpc(
            spec.Basic.Qos(prefetch_size, prefetch_count, global_qos), callback,
            [spec.Basic.QosOk])

    def basic_reject(self, delivery_tag: int = 0, requeue: bool = True) -> None:
        """
        Reject an incoming message.

        This method allows a client to reject a message. It can be used to interrupt and cancel
        large incoming messages, or return untreatable messages to their original queue.

        :param delivery_tag: int/long The server-assigned delivery tag
        :param requeue: If requeue is true, the server will attempt to requeue the message. If
            requeue is false or the requeue attempt fails the messages are discarded or dead-
            lettered.
        :raises TypeError:
        """
        self._raise_if_not_open()
        if not isinstance(delivery_tag, int):
            raise TypeError('delivery_tag must be an integer')
        return self._send_method(spec.Basic.Reject(delivery_tag, requeue))

    def basic_recover(self,
                      requeue: bool = False,
                      callback: _OnBasicRecoverCallback | None = None) -> None:
        """
        This method asks the server to redeliver all unacknowledged messages on a specified channel.
        Zero or more messages may be redelivered. This method replaces the asynchronous Recover.

        :param requeue: If False, the message will be redelivered to the original recipient. If
            True, the server will attempt to requeue the message, potentially then delivering it to
            an alternative subscriber.
        :param callback: callback(pika.frame.Method) for method Basic.RecoverOk
        :returns:``None``. Method frame from the Basic.Recover-ok response is delivered to
            ``callback`` when provided.
        :raises ValueError:
        """
        self._raise_if_not_open()
        validators.rpc_completion_callback(callback)
        return self._rpc(spec.Basic.Recover(requeue), callback,
                         [spec.Basic.RecoverOk])

    def close(self,
              reply_code: int = 0,
              reply_text: str = 'Normal shutdown') -> None:
        """
        Invoke a graceful shutdown of the channel with the AMQP Broker.

        If channel is OPENING, transition to CLOSING and suppress the incoming Channel.OpenOk, if
        any.

        :param reply_code: The reason code to send to broker
        :param reply_text: The reason text to send to broker
        :raises ChannelWrongStateError: if channel is closed or closing
        """
        if self.is_closed or self.is_closing:
            # Whoever is calling `close` might expect the on-channel-close-cb
            # to be called, which won't happen when it's already closed.
            self._raise_if_not_open()

        # If channel is OPENING, we will transition it to CLOSING state,
        # causing the _on_openok method to suppress the OPEN state transition
        # and the on-channel-open-callback

        LOGGER.info('Closing channel (%s): %r on %s', reply_code, reply_text,
                    self)

        # Save the reason info so that we may use it in the '_on_channel_close'
        # callback processing
        self._closing_reason = exceptions.ChannelClosedByClient(
            reply_code, reply_text)

        for consumer_tag in list(self._consumers.keys()):
            if consumer_tag not in self._cancelled:
                self.basic_cancel(consumer_tag=consumer_tag)

        # Change state after cancelling consumers to avoid
        # ChannelWrongStateError exception from basic_cancel
        self._set_state(self.CLOSING)

        self._rpc(spec.Channel.Close(reply_code, reply_text, 0, 0),
                  self._on_closeok, [spec.Channel.CloseOk])

    def confirm_delivery(
            self,
            ack_nack_callback: _OnAckNackCallback,
            callback: _OnConfirmDeliveryCallback | None = None) -> None:
        """
        Turn on Confirm mode in the channel.

        Pass in a callback to be notified by the Broker when a message has been confirmed as received or
        rejected (Basic.Ack, Basic.Nack) from the broker to the publisher.

        For more information see:
            https://www.rabbitmq.com/confirms.html

        :param ack_nack_callback: Required callback for delivery
            confirmations that has the following signature:
            callback(pika.frame.Method), where method_frame contains
            either method `spec.Basic.Ack` or `spec.Basic.Nack`.
        :param callback: callback(pika.frame.Method) for method
            Confirm.SelectOk
        :raises TypeError: if `ack_nack_callback` is not callable

        .. note::
            Calling this method more than once on the same channel replaces
            the previously registered ``ack_nack_callback`` rather than adding
            an additional one. Only the most recently registered callback
            receives ``Basic.Ack``/``Basic.Nack`` notifications.
        """
        if not callable(ack_nack_callback):
            # confirm_deliver requires a callback; it's meaningless
            # without a user callback to receive Basic.Ack/Basic.Nack notifications
            raise TypeError('confirm_delivery requires a callback '
                            'to receive Basic.Ack/Basic.Nack notifications')

        self._raise_if_not_open()
        nowait = validators.rpc_completion_callback(callback)

        if not (self.connection.publisher_confirms and
                self.connection.basic_nack):
            raise exceptions.MethodNotImplemented(
                'Confirm.Select not Supported by Server')

        # Replace any previously registered ack/nack callback so repeated
        # calls don't stack listeners and fire stale callbacks (see #1602).
        if self._on_ack_nack_callback is not None:
            self.callbacks.remove(self.channel_number, spec.Basic.Ack,
                                  self._on_ack_nack_callback)
            self.callbacks.remove(self.channel_number, spec.Basic.Nack,
                                  self._on_ack_nack_callback)

        # Add the ack and nack callback
        self.callbacks.add(self.channel_number, spec.Basic.Ack,
                           ack_nack_callback, False)
        self.callbacks.add(self.channel_number, spec.Basic.Nack,
                           ack_nack_callback, False)
        self._on_ack_nack_callback = ack_nack_callback

        self._rpc(spec.Confirm.Select(nowait), callback,
                  [spec.Confirm.SelectOk] if not nowait else [])

    @property
    def consumer_tags(self) -> list[str]:
        """Property method that returns a list of currently active consumers."""
        return list(self._consumers.keys())

    def exchange_bind(self,
                      destination: str,
                      source: str,
                      routing_key: str = '',
                      arguments: dict[str, Any] | None = None,
                      callback: _OnExchangeBindCallback | None = None) -> None:
        """
        Bind an exchange to another exchange.

        :param destination: The destination exchange to bind
        :param source: The source exchange to bind to
        :param routing_key: The routing key to bind on
        :param arguments: Custom key/value pair arguments for the binding
        :param callback: callback(pika.frame.Method) for method Exchange.BindOk
        :returns:``None``. Method frame from the Exchange.Bind-ok response is delivered to
            ``callback`` when synchronous (no ok frame in nowait mode).
        :raises ValueError:
        """
        self._raise_if_not_open()
        validators.require_string(destination, 'destination')
        validators.require_string(source, 'source')
        nowait = validators.rpc_completion_callback(callback)
        return self._rpc(
            spec.Exchange.Bind(0, destination, source, routing_key, nowait,
                               arguments or {}), callback,
            [spec.Exchange.BindOk] if not nowait else [])

    def exchange_declare(
            self,
            exchange: str,
            exchange_type: str = ExchangeType.direct,
            passive: bool = False,
            durable: bool = False,
            auto_delete: bool = False,
            internal: bool = False,
            arguments: dict[str, Any] | None = None,
            callback: _OnExchangeDeclareCallback | None = None) -> None:
        """
        This method creates an exchange if it does not already exist, and if the exchange exists,
        verifies that it is of the correct and expected class.

        If passive set, the server will reply with Declare-Ok if the exchange
        already exists with the same name, and raise an error if not and if the
        exchange does not already exist, the server MUST raise a channel
        exception with reply code 404 (not found).

        :param exchange: The exchange name consists of a non-empty sequence
            of these characters: letters, digits, hyphen, underscore, period,
            or colon
        :param exchange_type: The exchange type to use
        :param passive: Perform a declare or just check to see if it exists
        :param durable: Survive a reboot of RabbitMQ
        :param auto_delete: Remove when no more queues are bound to it
        :param internal: Can only be published to by other exchanges
        :param arguments: Custom key/value pair arguments for the exchange
        :param callback: callback(pika.frame.Method) for method Exchange.DeclareOk
        :returns: ``None``. Method frame from the Exchange.Declare-ok response is
            delivered to ``callback`` when synchronous (no ok frame in nowait
            mode).
        :raises ValueError:
        """
        validators.require_string(exchange, 'exchange')
        self._raise_if_not_open()
        nowait = validators.rpc_completion_callback(callback)
        if isinstance(exchange_type, Enum):
            exchange_type = exchange_type.value
        return self._rpc(
            spec.Exchange.Declare(0, exchange, exchange_type, passive, durable,
                                  auto_delete, internal, nowait, arguments or
                                  {}), callback,
            [spec.Exchange.DeclareOk] if not nowait else [])

    def exchange_delete(
            self,
            exchange: str | None = None,
            if_unused: bool = False,
            callback: _OnExchangeDeleteCallback | None = None) -> None:
        """
        Delete the exchange.

        :param exchange: The exchange name
        :param if_unused: only delete if the exchange is unused
        :param callback: callback(pika.frame.Method) for method Exchange.DeleteOk
        :returns:``None``. Method frame from the Exchange.Delete-ok response is delivered to
            ``callback`` when synchronous (no ok frame in nowait mode).
        :raises ValueError:
        """
        self._raise_if_not_open()
        nowait = validators.rpc_completion_callback(callback)
        return self._rpc(spec.Exchange.Delete(0, exchange, if_unused,
                                              nowait), callback,
                         [spec.Exchange.DeleteOk] if not nowait else [])

    def exchange_unbind(
            self,
            destination: str | None = None,
            source: str | None = None,
            routing_key: str = '',
            arguments: dict[str, Any] | None = None,
            callback: _OnExchangeUnbindCallback | None = None) -> None:
        """
        Unbind an exchange from another exchange.

        :param destination: The destination exchange to unbind
        :param source: The source exchange to unbind from
        :param routing_key: The routing key to unbind
        :param arguments: Custom key/value pair arguments for the binding
        :param callback: callback(pika.frame.Method) for method Exchange.UnbindOk
        :returns:``None``. Method frame from the Exchange.Unbind-ok response is delivered to
            ``callback`` when synchronous (no ok frame in nowait mode).
        :raises ValueError:
        """
        self._raise_if_not_open()
        nowait = validators.rpc_completion_callback(callback)
        return self._rpc(
            spec.Exchange.Unbind(0, destination, source, routing_key, nowait,
                                 arguments), callback,
            [spec.Exchange.UnbindOk] if not nowait else [])

    def flow(self,
             active: bool,
             callback: _OnFlowCallback | None = None) -> None:
        """
        Turn Channel flow control off and on.

        Pass a callback to be notified of the response from the server. active is a bool. Callback
        should expect a bool in response indicating channel flow state. For more information, please
        reference:

        https://www.rabbitmq.com/amqp-0-9-1-reference.html#channel.flow

        :param active: Turn flow on or off
        :param callback: callback(bool) upon completion
        :raises ValueError:
        """
        self._raise_if_not_open()
        validators.rpc_completion_callback(callback)
        self._on_flowok_callback = callback
        self._rpc(spec.Channel.Flow(active), self._on_flowok,
                  [spec.Channel.FlowOk])

    @property
    def is_closed(self) -> bool:
        """Returns True if the channel is closed."""
        return self._state == self.CLOSED

    @property
    def is_closing(self) -> bool:
        """Returns True if client-initiated closing of the channel is in progress."""
        return self._state == self.CLOSING

    @property
    def is_open(self) -> bool:
        """Returns True if the channel is open."""
        return self._state == self.OPEN

    @property
    def is_opening(self) -> bool:
        """Returns True if the channel is opening."""
        return self._state == self.OPENING

    def open(self) -> None:
        """Open the channel."""
        self._set_state(self.OPENING)
        self._add_callbacks()
        self._rpc(spec.Channel.Open(), self._on_openok, [spec.Channel.OpenOk])

    def queue_bind(self,
                   queue: str,
                   exchange: str,
                   routing_key: str | None = None,
                   arguments: dict[str, Any] | None = None,
                   callback: _OnQueueBindCallback | None = None) -> None:
        """
        Bind the queue to the specified exchange.

        :param queue: The queue to bind to the exchange
        :param exchange: The source exchange to bind to
        :param routing_key: The routing key to bind on
        :param arguments: Custom key/value pair arguments for the binding
        :param callback: callback(pika.frame.Method) for method Queue.BindOk
        :returns:``None``. Method frame from the Queue.Bind-ok response is delivered to ``callback``
            when synchronous (no ok frame in nowait mode).
        :raises ValueError:
        """
        validators.require_string(queue, 'queue')
        validators.require_string(exchange, 'exchange')
        self._raise_if_not_open()
        nowait = validators.rpc_completion_callback(callback)
        if routing_key is None:
            routing_key = queue
        return self._rpc(
            spec.Queue.Bind(0, queue, exchange, routing_key, nowait,
                            arguments or {}), callback,
            [spec.Queue.BindOk] if not nowait else [])

    def queue_declare(self,
                      queue: str,
                      passive: bool = False,
                      durable: bool = False,
                      exclusive: bool = False,
                      auto_delete: bool = False,
                      arguments: dict[str, Any] | None = None,
                      callback: _OnQueueDeclareCallback | None = None) -> None:
        """
        Declare queue, create if needed.

        This method creates or checks a queue. When creating a new queue the client can specify various
        properties that control the durability of the queue and its contents,
        and the level of sharing for the queue.

        Use an empty string as the queue name for the broker to auto-generate
        one

        :param queue: The queue name; if empty string, the broker will
            create a unique queue name
        :param passive: Only check to see if the queue exists
        :param durable: Survive reboots of the broker
        :param exclusive: Only allow access by the current connection
        :param auto_delete: Delete after consumer cancels or disconnects
        :param arguments: Custom key/value arguments for the queue
        :param callback: callback(pika.frame.Method) for method Queue.DeclareOk
        :returns: ``None``. Method frame from the Queue.Declare-ok response is
            delivered to ``callback`` when synchronous (no ok frame in nowait
            mode).
        :raises ValueError:
        """
        validators.require_string(queue, 'queue')
        self._raise_if_not_open()
        nowait = validators.rpc_completion_callback(callback)

        condition: Any
        if queue:
            condition = (spec.Queue.DeclareOk, {'queue': queue})
        else:
            condition = spec.Queue.DeclareOk
        replies = [condition] if not nowait else []

        return self._rpc(
            spec.Queue.Declare(0, queue, passive, durable, exclusive,
                               auto_delete, nowait, arguments or {}), callback,
            replies)

    def queue_delete(self,
                     queue: str,
                     if_unused: bool = False,
                     if_empty: bool = False,
                     callback: _OnQueueDeleteCallback | None = None) -> None:
        """
        Delete a queue from the broker.

        :param queue: The queue to delete
        :param if_unused: only delete if it's unused
        :param if_empty: only delete if the queue is empty
        :param callback: callback(pika.frame.Method) for method Queue.DeleteOk
        :returns:``None``. Method frame from the Queue.Delete-ok response is delivered to
            ``callback`` when synchronous (no ok frame in nowait mode).
        :raises ValueError:
        """
        self._raise_if_not_open()
        validators.require_string(queue, 'queue')
        nowait = validators.rpc_completion_callback(callback)
        replies = [spec.Queue.DeleteOk] if not nowait else []
        return self._rpc(
            spec.Queue.Delete(0, queue, if_unused, if_empty, nowait), callback,
            replies)

    def queue_purge(self,
                    queue: str,
                    callback: _OnQueuePurgeCallback | None = None) -> None:
        """
        Purge all of the messages from the specified queue.

        :param queue: The queue to purge
        :param callback: callback(pika.frame.Method) for method Queue.PurgeOk
        :returns:``None``. Method frame from the Queue.Purge-ok response is delivered to
            ``callback`` when synchronous (no ok frame in nowait mode).
        :raises ValueError:
        """
        self._raise_if_not_open()
        validators.require_string(queue, 'queue')
        nowait = validators.rpc_completion_callback(callback)
        replies = [spec.Queue.PurgeOk] if not nowait else []
        return self._rpc(spec.Queue.Purge(0, queue, nowait), callback, replies)

    def queue_unbind(self,
                     queue: str,
                     exchange: str | None = None,
                     routing_key: str | None = None,
                     arguments: dict[str, Any] | None = None,
                     callback: _OnQueueUnbindCallback | None = None) -> None:
        """
        Unbind a queue from an exchange.

        :param queue: The queue to unbind from the exchange
        :param exchange: The source exchange to bind from
        :param routing_key: The routing key to unbind
        :param arguments: Custom key/value pair arguments for the binding
        :param callback: callback(pika.frame.Method) for method Queue.UnbindOk
        :returns:``None``. Method frame from the Queue.Unbind-ok response is delivered to
            ``callback`` when provided.
        :raises ValueError:
        """
        self._raise_if_not_open()
        validators.require_string(queue, 'queue')
        validators.rpc_completion_callback(callback)
        if routing_key is None:
            routing_key = queue
        return self._rpc(
            spec.Queue.Unbind(0, queue, exchange, routing_key, arguments or {}),
            callback, [spec.Queue.UnbindOk])

    def tx_commit(self, callback: _OnTxCommitCallback | None = None) -> None:
        """
        Commit a transaction.

        :param callback: callback(pika.frame.Method) for method Tx.CommitOk
        :returns:``None``. Method frame from the Tx.Commit-ok response is delivered to ``callback``
            when provided.
        :raises ValueError:
        """
        self._raise_if_not_open()
        validators.rpc_completion_callback(callback)
        return self._rpc(spec.Tx.Commit(), callback, [spec.Tx.CommitOk])

    def tx_rollback(self,
                    callback: _OnTxRollbackCallback | None = None) -> None:
        """
        Rollback a transaction.

        :param callback: callback(pika.frame.Method) for method Tx.RollbackOk
        :returns:``None``. Method frame from the Tx.Rollback-ok response is delivered to
            ``callback`` when provided.
        :raises ValueError:
        """
        self._raise_if_not_open()
        validators.rpc_completion_callback(callback)
        return self._rpc(spec.Tx.Rollback(), callback, [spec.Tx.RollbackOk])

    def tx_select(self, callback: _OnTxSelectCallback | None = None) -> None:
        """
        Select standard transaction mode.

        This method sets the channel to use standard transactions. The client must use this method
        at least once on a channel before using the Commit or Rollback methods.

        :param callback: callback(pika.frame.Method) for method Tx.SelectOk
        :returns:``None``. Method frame from the Tx.Select-ok response is delivered to ``callback``
            when provided.
        :raises ValueError:
        """
        self._raise_if_not_open()
        validators.rpc_completion_callback(callback)
        return self._rpc(spec.Tx.Select(), callback, [spec.Tx.SelectOk])

    # Internal methods

    def _add_callbacks(self) -> None:
        """Callbacks that add the required behavior for a channel when connecting and connected to a
        server.
        """
        # Add a callback for Basic.GetEmpty
        self.callbacks.add(self.channel_number, spec.Basic.GetEmpty,
                           self._on_getempty, False)

        # Add a callback for Basic.Cancel
        self.callbacks.add(self.channel_number, spec.Basic.Cancel,
                           self._on_cancel, False)

        # Deprecated in newer versions of RabbitMQ but still register for it
        self.callbacks.add(self.channel_number, spec.Channel.Flow,
                           self._on_flow, False)

        # Add a callback for when the server closes our channel
        self.callbacks.add(self.channel_number, spec.Channel.Close,
                           self._on_close_from_broker, True)

    def _add_on_cleanup_callback(self, callback: Callable[..., Any]) -> None:
        """
        For internal use only (e.g., Connection needs to remove closed channels from its channel
        container). Pass a callback function that will be called when the channel is being cleaned
        up after all channel-close callbacks callbacks.

        :param callback: The callback to call, having the
            signature: callback(channel)
        """
        self.callbacks.add(self.channel_number,
                           self._ON_CHANNEL_CLEANUP_CB_KEY,
                           callback,
                           one_shot=True,
                           only_caller=self)

    def _cleanup(self) -> None:
        """Remove all consumers and any callbacks for the channel."""
        self.callbacks.process(self.channel_number,
                               self._ON_CHANNEL_CLEANUP_CB_KEY, self, self)
        self._consumers = {}
        self._cancelled = set()
        self._nowait_cancelled = deque()
        self._consumers_with_noack = set()
        self.callbacks.cleanup(str(self.channel_number))
        self._cookie = None

    def _cleanup_consumer_ref(self, consumer_tag: str) -> None:
        """
        Remove any references to the consumer tag in internal structures for consumer state.

        :param consumer_tag: The consumer tag to cleanup
        """
        self._consumers_with_noack.discard(consumer_tag)
        self._consumers.pop(consumer_tag, None)
        self._cancelled.discard(consumer_tag)

    def _retain_cancelled_tag(self, consumer_tag: str) -> None:
        """
        Retain a nowait-cancelled consumer tag, evicting the oldest once the cap is reached.

        A cancelled tag stays in `_cancelled` (and `_consumers_with_noack`) so that a delivery the
        broker had already dispatched when `Basic.Cancel` was sent is rejected rather than left
        unacknowledged; see `_on_deliver`.  A cancel that expects a `Basic.CancelOk` retires its own
        entry in `_on_cancelok`, but a nowait cancel asks the broker for no reply, so nothing
        retires it and the entries would otherwise accumulate for the life of the channel.

        Bound them here instead.  The number of deliveries that can still be in flight for a
        cancelled consumer is bounded by what the broker had already dispatched, so a cap on
        retained nowait-cancelled tags approximates that window: evicting in cancellation order past
        `_MAX_RETAINED_CANCELLED_TAGS` keeps retention constant in the number of cancels.  The cap
        is not the true window, though, since it is measured in cancels rather than deliveries, so
        once a tag is evicted its reject-and-reserve behaviour lapses: a straggling delivery for it
        is logged as unexpected and left unacknowledged (see `_on_deliver`), and `basic_consume`
        will accept the tag again.  The default is large enough that this only occurs under extreme
        nowait-cancel churn.

        A tag cannot be queued twice: `basic_consume` refuses a tag that is still in `_cancelled`,
        and on the nowait path only eviction takes it back out again.

        :param consumer_tag: The consumer tag just cancelled with nowait
        """
        self._nowait_cancelled.append(consumer_tag)
        while len(self._nowait_cancelled) > self._MAX_RETAINED_CANCELLED_TAGS:
            self._cleanup_consumer_ref(self._nowait_cancelled.popleft())

    def _get_cookie(self) -> Any:
        """
        Used by the wrapper implementation (e.g., `BlockingChannel`) to retrieve the cookie that it
        set via `_set_cookie`

        :returns: opaque cookie value that was set via `_set_cookie`
        """
        return self._cookie

    def _handle_content_frame(self, frame_value: frame.Frame) -> None:
        """
        This is invoked by the connection when frames that are not registered with the
        CallbackManager have been found. This should only be the case when the frames are related to
        content delivery.

        The _content_assembler will be invoked which will return the fully formed message in three
        parts when all of the body frames have been received.

        :param frame_value: The frame to deliver
        """
        try:
            response = self._content_assembler.process(frame_value)
        except exceptions.UnexpectedFrameError:
            self._on_unexpected_frame(frame_value)
            return

        if response:
            method_index = response[0].method.INDEX
            if method_index == spec.Basic.Deliver.INDEX:
                self._on_deliver(*response)
            elif method_index == spec.Basic.GetOk.INDEX:
                self._on_getok(*response)
            elif method_index == spec.Basic.Return.INDEX:
                self._on_return(*response)

    def _on_cancel(self, method_frame: frame.Method) -> None:
        """
        When the broker cancels a consumer, delete it from our internal dictionary.

        Reply with `Basic.CancelOk` if the broker advertises the `accept_consumer_cancel_ok`
        capability.

        :param method_frame: The method frame received
        """
        consumer_tag = method_frame.method.consumer_tag
        # Sent before the `_cancelled` check below, so a user-initiated cancel
        # racing a broker-sent one still gets a reply. That is safe in both
        # orders, which is not obvious from here. A broker advertising the
        # capability answers a `Basic.CancelOk` for a tag it is not waiting on
        # with `{noreply, State}`, so a late or duplicate reply is ignored
        # rather than treated as a protocol error. And if this reply reaches the
        # broker first, it releases the consumer without replying, leaving the
        # user's in-flight `Basic.Cancel` to arrive for a tag the broker no
        # longer tracks - which `cancel_consumer` answers with a `Basic.CancelOk`
        # anyway ("Spec requires we ignore this situation"), so the pending RPC
        # still completes instead of hanging.
        if self.is_open and self.connection.accept_consumer_cancel_ok:
            self._send_method(spec.Basic.CancelOk(consumer_tag=consumer_tag))

        if consumer_tag in self._cancelled:
            # User-initiated cancel is waiting for Cancel-ok
            return

        self._cleanup_consumer_ref(consumer_tag)

    def _on_cancelok(self, method_frame: frame.Method) -> None:
        """
        Called in response to a frame from the Broker when the client sends Basic.Cancel.

        :param method_frame: The method frame received
        """
        self._cleanup_consumer_ref(method_frame.method.consumer_tag)

    def _transition_to_closed(self) -> None:
        """Common logic for transitioning the channel to the CLOSED state:

        Set state to CLOSED, dispatch callbacks registered via
        `Channel.add_on_close_callback()`, and mop up.

        Assumes that the channel is not in CLOSED state and that
        `self._closing_reason` has been set up

        """
        assert not self.is_closed
        assert self._closing_reason is not None

        self._set_state(self.CLOSED)

        try:
            self.callbacks.process(self.channel_number, '_on_channel_close',
                                   self, self, self._closing_reason)
        finally:
            self._cleanup()

    def _on_close_from_broker(self, method_frame: frame.Method) -> None:
        """
        Handle `Channel.Close` from broker.

        :param method_frame: Method frame with Channel.Close method
        """
        LOGGER.warning('Received remote Channel.Close (%s): %r on %s',
                       method_frame.method.reply_code,
                       method_frame.method.reply_text, self)
        # Note, we should not be called when channel is already closed
        assert not self.is_closed

        # AMQP 0.9.1 requires CloseOk response to Channel.Close;
        self._send_method(spec.Channel.CloseOk())

        # Save the details, possibly overriding user-provided values if
        # user-initiated close is pending (in which case they will be provided
        # to user callback when CloseOk arrives).
        self._closing_reason = exceptions.ChannelClosedByBroker(
            method_frame.method.reply_code, method_frame.method.reply_text)

        if self.is_closing:
            # Since we may have already put Channel.Close on the wire, we need
            # to wait for CloseOk before cleaning up to avoid a race condition
            # whereby our channel number might get reused before our CloseOk
            # arrives
            #
            # NOTE: if our Channel.Close destined for the broker was blocked by
            # an earlier synchronous method, this call will drop it and perform
            # a meta-close (see `_on_close_meta()` which fakes receipt of
            # `Channel.CloseOk` and dispatches the `'_on_channel_close'`
            # callbacks.
            self._drain_blocked_methods_on_remote_close()
        else:
            self._transition_to_closed()

    def _on_close_meta(self, reason: Exception | None) -> None:
        """
        Handle meta-close request from either a remote Channel.Close from the broker (when a pending
        Channel.Close method is queued for execution) or a Connection's cleanup logic after sudden
        connection loss. We use this opportunity to transition to CLOSED state, clean up the
        channel, and dispatch the on-channel-closed callbacks.

        :param reason: Exception describing the reason for closing.
        """
        LOGGER.debug('Handling meta-close on %s: %r', self, reason)

        if not self.is_closed:
            self._closing_reason = reason
            self._transition_to_closed()

    def _on_closeok(self, method_frame: frame.Method) -> None:
        """
        Invoked when RabbitMQ replies to a Channel.Close method.

        :param method_frame: Method frame with Channel.CloseOk method
        """
        LOGGER.info('Received %s on %s', method_frame.method, self)

        self._transition_to_closed()

    def _on_deliver(self, method_frame: frame.Method,
                    header_frame: frame.Header, body: bytes) -> None:
        """
        Cope with reentrancy.

        If a particular consumer is still active when another delivery appears for it, queue the
        deliveries up until it finally exits.

        :param method_frame: The method frame received
        :param header_frame: The header frame received
        :param body: The body received
        """
        consumer_tag = method_frame.method.consumer_tag

        if consumer_tag in self._cancelled:
            if self.is_open and consumer_tag not in self._consumers_with_noack:
                self.basic_reject(method_frame.method.delivery_tag)
            return

        if consumer_tag not in self._consumers:
            LOGGER.error('Unexpected delivery: %r', method_frame)
            return

        self._consumers[consumer_tag](self, method_frame.method,
                                      header_frame.properties, body)

    def _on_eventok(self, method_frame: frame.Method) -> None:
        """
        Generic events that returned ok that may have internal callbacks.

        We keep a list of what we've yet to implement so that we don't silently drain events that we
        don't support.

        :param method_frame: The method frame received
        """
        LOGGER.debug('Discarding frame %r', method_frame)

    def _on_flow(self, _method_frame_unused: frame.Method) -> None:
        """
        Called if the server sends a Channel.Flow frame.

        :param _method_frame_unused: The Channel.Flow frame
        """
        if self._has_on_flow_callback is False:
            LOGGER.warning('Channel.Flow received from server')

    def _on_flowok(self, method_frame: frame.Method) -> None:
        """
        Called in response to us asking the server to toggle on Channel.Flow.

        :param method_frame: The method frame received
        """
        self.flow_active = method_frame.method.active
        if self._on_flowok_callback:
            self._on_flowok_callback(method_frame.method.active)
            self._on_flowok_callback = None
        else:
            LOGGER.warning('Channel.FlowOk received with no active callbacks')

    def _on_getempty(self, method_frame: frame.Method) -> None:
        """
        When we receive an empty reply do nothing but log it.

        :param method_frame: The method frame received
        """
        LOGGER.debug('Received Basic.GetEmpty: %r', method_frame)
        if self._on_getok_callback is not None:
            self._on_getok_callback = None

    def _on_getok(self, method_frame: frame.Method, header_frame: frame.Header,
                  body: bytes) -> None:
        """
        Called in reply to a Basic.Get when there is a message.

        :param method_frame: The method frame received
        :param header_frame: The header frame received
        :param body: The body received
        """
        if self._on_getok_callback is not None:
            callback = self._on_getok_callback
            self._on_getok_callback = None
            callback(self, method_frame.method, header_frame.properties, body)
        else:
            LOGGER.error('Basic.GetOk received with no active callback')

    def _on_openok(self, method_frame: frame.Method) -> None:
        """
        Called by our callback handler when we receive a Channel.OpenOk and subsequently calls our
        _on_openok_callback which was passed into the Channel constructor. The reason we do this is
        because we want to make sure that the on_open_callback parameter passed into the Channel
        constructor is not the first callback we make.

        Suppress the state transition and callback if channel is already in CLOSING state.

        :param method_frame: Channel.OpenOk frame
        """
        # Suppress OpenOk if the user or Connection.Close started closing it
        # before open completed.
        if self.is_closing:
            LOGGER.debug('Suppressing while in closing state: %s', method_frame)
        else:
            self._set_state(self.OPEN)
            if self._on_openok_callback is not None:
                self._on_openok_callback(self)

    def _on_return(self, method_frame: frame.Method, header_frame: frame.Header,
                   body: bytes) -> None:
        """
        Called if the server sends a Basic.Return frame.

        :param method_frame: The Basic.Return frame
        :param header_frame: The content header frame
        :param body: The message body
        """
        if not self.callbacks.process(self.channel_number, '_on_return', self,
                                      self, method_frame.method,
                                      header_frame.properties, body):
            LOGGER.debug('Basic.Return received from server (%r, %r)',
                         method_frame.method, header_frame.properties)

    def _on_selectok(self, method_frame: frame.Method) -> None:
        """
        Called when the broker sends a Confirm.SelectOk frame.

        :param method_frame: The method frame received
        """
        LOGGER.debug('Confirm.SelectOk Received: %r', method_frame)

    def _on_synchronous_complete(self,
                                 _method_frame_unused: frame.Method) -> None:
        """
        This is called when a synchronous command is completed.

        It will undo the blocking state and send all the frames that stacked up while we were in the
        blocking state.

        :param _method_frame_unused: The method frame received
        """
        LOGGER.debug('%i blocked frames', len(self._blocked))
        self._blocking = None
        # self._blocking must be checked here as a callback could
        # potentially change the state of that variable during an
        # iteration of the while loop
        while self._blocked and self._blocking is None:
            self._rpc(*self._blocked.popleft())

    def _drain_blocked_methods_on_remote_close(self) -> None:
        """
        This is called when the broker sends a Channel.Close while the client is in CLOSING state.
        This method checks the blocked method queue for a pending client-initiated Channel.Close
        method and ensures its callbacks are processed, but does not send the method to the broker.

        The broker may close the channel before responding to outstanding in-transit synchronous
        methods, or even before these methods have been sent to the broker. AMQP 0.9.1 obliges the
        server to drop all methods arriving on a closed channel other than Channel.CloseOk and
        Channel.Close. Since the response to a synchronous method that blocked the channel never
        arrives, the channel never becomes unblocked, and the Channel.Close, if any, in the blocked
        queue has no opportunity to be sent, and thus its completion callback would never be called.
        """
        LOGGER.debug(
            'Draining %i blocked frames due to broker-requested Channel.Close',
            len(self._blocked))
        while self._blocked:
            method = self._blocked.popleft()[0]
            if isinstance(method, spec.Channel.Close):
                # The desired reason is already in self._closing_reason
                self._on_close_meta(self._closing_reason)
            else:
                LOGGER.debug('Ignoring drained blocked method: %s', method)

    def _rpc(
        self,
        method: amqp_object.Method,
        callback: Callable[..., Any] | None = None,
        acceptable_replies: Sequence[type[amqp_object.Method] |
                                     tuple[type[amqp_object.Method],
                                           dict[str, Any]]] | None = None
    ) -> None:
        """
        Make a synchronous channel RPC call for a synchronous method frame.

        If the channel is already in the blocking state, then enqueue the request,
        but don't send it at this time; it will be eventually sent by
        `_on_synchronous_complete` after the prior blocking request receives a
        response. If the channel is not in the blocking state and
        `acceptable_replies` is not empty, transition the channel to the
        blocking state and register for `_on_synchronous_complete` before
        sending the request.

        NOTE: A callback must be accompanied by non-empty acceptable_replies.

        :param method: The AMQP method to invoke
        :param callback: The callback for the RPC response
        :param acceptable_replies: A (possibly empty) sequence of
            replies this RPC call expects or None
        """
        assert method.synchronous, (
            f'Only synchronous-capable methods may be used with _rpc: {method!r}'
        )

        # Validate we got None or a list of acceptable_replies
        if not isinstance(acceptable_replies, (type(None), list)):
            raise TypeError('acceptable_replies should be list or None')

        if callback is not None:
            # Validate the callback is callable
            if not callable(callback):
                raise TypeError('callback should be None or a callable')

            # Make sure that callback is accompanied by acceptable replies
            if not acceptable_replies:
                raise ValueError(
                    'Unexpected callback for asynchronous (nowait) operation.')

        # Make sure the channel is not closed yet
        if self.is_closed:
            self._raise_if_not_open()

        # If the channel is blocking, add subsequent commands to our stack
        if self._blocking:
            LOGGER.debug(
                'Already in blocking state, so enqueueing method %s; '
                'acceptable_replies=%r', method, acceptable_replies)
            self._blocked.append([method, callback, acceptable_replies])
            return

        # Note: _send_method can throw exceptions if there are framing errors
        # or invalid data passed in. Call it here to prevent self._blocking
        # from being set if an exception is thrown. This also prevents
        # acceptable_replies registering callbacks when exceptions are thrown
        self._send_method(method)

        # If acceptable replies are set, add callbacks
        if acceptable_replies:
            # Block until a response frame is received for synchronous frames
            self._blocking = method.NAME
            LOGGER.debug(
                'Entering blocking state on frame %s; acceptable_replies=%r',
                method, acceptable_replies)

            for reply in acceptable_replies:
                if isinstance(reply, tuple):
                    reply, arguments = reply
                else:
                    arguments = None
                LOGGER.debug('Adding on_synchronous_complete callback')
                self.callbacks.add(self.channel_number,
                                   reply,
                                   self._on_synchronous_complete,
                                   arguments=arguments)
                if callback is not None:
                    LOGGER.debug('Adding passed-in RPC response callback')
                    self.callbacks.add(self.channel_number,
                                       reply,
                                       callback,
                                       arguments=arguments)

    def _raise_if_not_open(self) -> None:
        """
        If channel is not in the OPEN state, raises ChannelWrongStateError with `reply_code` and
        `reply_text` corresponding to current state.

        :raises exceptions.ChannelWrongStateError: if channel is not in OPEN state.
        """
        if self._state == self.OPEN:
            return

        if self._state == self.OPENING:
            raise exceptions.ChannelWrongStateError(
                'Channel is opening, but is not usable yet.')

        if self._state == self.CLOSING:
            raise exceptions.ChannelWrongStateError('Channel is closing.')

        # Assumed self.CLOSED
        assert self._state == self.CLOSED
        raise exceptions.ChannelWrongStateError('Channel is closed.')

    def _send_method(
            self,
            method: amqp_object.Method,
            content: tuple[spec.BasicProperties, bytes] | None = None) -> None:
        """
        Shortcut wrapper to send a method through our connection, passing in the channel number.

        :param method: The method to send
        :param content: If set, is a content frame, is tuple of properties and body.
        """
        self.connection._send_method(self.channel_number, method, content)

    def _set_cookie(self, cookie: object) -> None:
        """
        Used by wrapper layer (e.g., `BlockingConnection`) to link the channel implementation back
        to the proxy. See `_get_cookie`.

        :param cookie: an opaque value; typically a proxy channel implementation instance (e.g.,
            `BlockingChannel` instance)
        """
        self._cookie = cookie

    def _set_state(self, connection_state: int) -> None:
        """
        Set the channel connection state to the specified state value.

        :param connection_state: The connection_state value
        """
        self._state = connection_state

    def _on_unexpected_frame(self, frame_value: frame.Frame) -> None:
        """
        Invoked when a frame is received that is not setup to be processed.

        :param frame_value: The frame received
        """
        LOGGER.error('Unexpected frame: %r', frame_value)

consumer_tags property

consumer_tags: list[str]

Property method that returns a list of currently active consumers.

is_closed property

is_closed: bool

Returns True if the channel is closed.

is_closing property

is_closing: bool

Returns True if client-initiated closing of the channel is in progress.

is_open property

is_open: bool

Returns True if the channel is open.

is_opening property

is_opening: bool

Returns True if the channel is opening.

__init__

__init__(
    connection: Connection,
    channel_number: int,
    on_open_callback: _OnOpenCallback | None,
) -> None

Create a new instance of the Channel.

PARAMETER DESCRIPTION
connection

The connection

TYPE: Connection

channel_number

The channel number for this instance

TYPE: int

on_open_callback

The callback to call on channel open. The callback will be invoked with the Channel instance as its only argument.

TYPE: _OnOpenCallback | None

Source code in pika/channel.py
def __init__(self, connection: Connection, channel_number: int,
             on_open_callback: _OnOpenCallback | None) -> None:
    """
    Create a new instance of the Channel.

    :param connection: The connection
    :param channel_number: The channel number for this instance
    :param on_open_callback: The callback to call on channel open. The callback will be invoked
        with the `Channel` instance as its only argument.
    """
    if not isinstance(channel_number, int):
        raise exceptions.InvalidChannelNumber(channel_number)

    validators.rpc_completion_callback(on_open_callback)

    self.channel_number = channel_number
    self.callbacks = connection.callbacks
    self.connection = connection

    # Initially, flow is assumed to be active
    self.flow_active = True

    self._content_assembler = ContentFrameAssembler()

    self._blocked: deque = deque()
    self._blocking: Any | None = None
    self._has_on_flow_callback: bool = False
    self._cancelled: set = set()
    # Nowait-cancelled tags in cancellation order, bounding how many of
    # them `_cancelled` retains; see `_retain_cancelled_tag`.
    self._nowait_cancelled: deque = deque()
    self._consumers: dict = {}
    self._consumers_with_noack: set = set()
    self._on_flowok_callback: Callable[..., Any] | None = None
    self._on_getok_callback: Callable[..., Any] | None = None
    self._on_ack_nack_callback: _OnAckNackCallback | None = None
    self._on_openok_callback: Callable[..., Any] | None = on_open_callback
    self._state: int = self.CLOSED

    # We save the closing reason exception to be passed to on-channel-close
    # callback at closing of the channel. Exception representing the closing
    # reason; ChannelClosedByClient or ChannelClosedByBroker on controlled
    # close; otherwise another exception describing the reason for failure
    # (most likely connection failure).
    self._closing_reason = None  # type: None | Exception

    # opaque cookie value set by wrapper layer (e.g., BlockingConnection)
    # via _set_cookie
    self._cookie: object = None

__int__

__int__() -> int

Return the channel object as its channel number.

Source code in pika/channel.py
def __int__(self) -> int:
    """Return the channel object as its channel number."""
    return self.channel_number

add_callback

add_callback(
    callback: Callable[..., Any],
    replies: Sequence[type[Method]],
    one_shot: bool = True,
) -> None

Pass in a callback handler and a list replies from the RabbitMQ broker which you'd like the callback notified of. Callbacks should allow for the frame parameter to be passed in.

PARAMETER DESCRIPTION
callback

The callback to call

TYPE: Callable[..., Any]

replies

The replies to get a callback for

TYPE: Sequence[type[Method]]

one_shot

Only handle the first type callback

TYPE: bool DEFAULT: True

Source code in pika/channel.py
def add_callback(self,
                 callback: Callable[..., Any],
                 replies: Sequence[type[amqp_object.Method]],
                 one_shot: bool = True) -> None:
    """
    Pass in a callback handler and a list replies from the RabbitMQ broker which you'd like the
    callback notified of. Callbacks should allow for the frame parameter to be passed in.

    :param callback: The callback to call
    :param replies: The replies to get a callback for
    :param one_shot: Only handle the first type callback
    """
    for reply in replies:
        self.callbacks.add(self.channel_number, reply, callback, one_shot)

add_on_cancel_callback

add_on_cancel_callback(callback: _OnCancelCallback) -> None

Pass a callback function that will be called when the basic_cancel is sent by the server. The callback function should receive a frame parameter.

PARAMETER DESCRIPTION
callback

The callback to call on Basic.Cancel from broker

TYPE: _OnCancelCallback

Source code in pika/channel.py
def add_on_cancel_callback(self, callback: _OnCancelCallback) -> None:
    """
    Pass a callback function that will be called when the basic_cancel is sent by the server.
    The callback function should receive a frame parameter.

    :param callback: The callback to call on Basic.Cancel from broker
    """
    self.callbacks.add(self.channel_number, spec.Basic.Cancel, callback,
                       False)

add_on_close_callback

add_on_close_callback(callback: _OnCloseCallback) -> None

Pass a callback function that will be called when the channel is closed.

The callback function will receive the channel and an exception describing why the channel was closed.

If the channel is closed by broker via Channel.Close, the callback will receive ChannelClosedByBroker as the reason.

If graceful user-initiated channel closing completes successfully ( either directly of indirectly by closing a connection containing the channel) and closing concludes gracefully without Channel.Close from the broker and without loss of connection, the callback will receive ChannelClosedByClient exception as reason.

If channel was closed due to loss of connection, the callback will receive another exception type describing the failure.

PARAMETER DESCRIPTION
callback

The callback, having the signature: callback(Channel, Exception reason)

TYPE: _OnCloseCallback

Source code in pika/channel.py
def add_on_close_callback(self, callback: _OnCloseCallback) -> None:
    """
    Pass a callback function that will be called when the channel is closed.

    The callback function will receive the channel and an exception describing why the channel
    was closed.

    If the channel is closed by broker via Channel.Close, the callback will receive
    `ChannelClosedByBroker` as the reason.

    If graceful user-initiated channel closing completes successfully ( either directly of
    indirectly by closing a connection containing the channel) and closing concludes gracefully
    without Channel.Close from the broker and without loss of connection, the callback will
    receive `ChannelClosedByClient` exception as reason.

    If channel was closed due to loss of connection, the callback will receive another exception
    type describing the failure.

    :param callback: The callback, having the signature: callback(Channel, Exception reason)
    """
    self.callbacks.add(self.channel_number, '_on_channel_close', callback,
                       False, self)

add_on_flow_callback

add_on_flow_callback(callback: _OnFlowCallback) -> None

Pass a callback function that will be called when Channel.Flow is called by the remote server. Note that newer versions of RabbitMQ will not issue this but instead use TCP backpressure.

PARAMETER DESCRIPTION
callback

The callback function

TYPE: _OnFlowCallback

Source code in pika/channel.py
def add_on_flow_callback(self, callback: _OnFlowCallback) -> None:
    """
    Pass a callback function that will be called when Channel.Flow is called by the remote
    server. Note that newer versions of RabbitMQ will not issue this but instead use TCP
    backpressure.

    :param callback: The callback function
    """
    self._has_on_flow_callback = True
    self.callbacks.add(self.channel_number, spec.Channel.Flow, callback,
                       False)

add_on_return_callback

add_on_return_callback(callback: _OnReturnCallback) -> None

Pass a callback function that will be called when basic_publish is sent a message that has been rejected and returned by the server.

PARAMETER DESCRIPTION
callback

The function to call, having the signature callback(channel, method, properties, body) where - channel: pika.channel.Channel - method: pika.spec.Basic.Return - properties: pika.spec.BasicProperties - body: bytes

TYPE: _OnReturnCallback

Source code in pika/channel.py
def add_on_return_callback(self, callback: _OnReturnCallback) -> None:
    """
    Pass a callback function that will be called when basic_publish is sent a message that has
    been rejected and returned by the server.

    :param callback: The function to call, having the signature
                            callback(channel, method, properties, body)
                            where
                            - channel: pika.channel.Channel
                            - method: pika.spec.Basic.Return
                            - properties: pika.spec.BasicProperties
                            - body: bytes
    """
    self.callbacks.add(self.channel_number, '_on_return', callback, False)

basic_ack

basic_ack(
    delivery_tag: int = 0, multiple: bool = False
) -> None

Acknowledge one or more messages.

When sent by the client, this method acknowledges one or more messages delivered via the Deliver or Get-Ok methods. When sent by server, this method acknowledges one or more messages published with the Publish method on a channel in confirm mode. The acknowledgement can be for a single message or a set of messages up to and including a specific message.

PARAMETER DESCRIPTION
delivery_tag

int/long The server-assigned delivery tag

TYPE: int DEFAULT: 0

multiple

If set to True, the delivery tag is treated as "up to and including", so that multiple messages can be acknowledged with a single method. If set to False, the delivery tag refers to a single message. If the multiple field is 1, and the delivery tag is zero, this indicates acknowledgement of all outstanding messages.

TYPE: bool DEFAULT: False

Source code in pika/channel.py
def basic_ack(self, delivery_tag: int = 0, multiple: bool = False) -> None:
    """
    Acknowledge one or more messages.

    When sent by the client, this method acknowledges one or more messages delivered via the
    Deliver or Get-Ok methods. When sent by server, this method acknowledges one or more
    messages published with the Publish method on a channel in confirm mode. The acknowledgement
    can be for a single message or a set of messages up to and including a specific message.

    :param delivery_tag: int/long The server-assigned delivery tag
    :param multiple: If set to True, the delivery tag is treated as "up to and including", so
        that multiple messages can be acknowledged with a single method. If set to False, the
        delivery tag refers to a single message. If the multiple field is 1, and the delivery
        tag is zero, this indicates acknowledgement of all outstanding messages.
    """
    self._raise_if_not_open()
    return self._send_method(spec.Basic.Ack(delivery_tag, multiple))

basic_cancel

basic_cancel(
    consumer_tag: str = '',
    callback: _OnBasicCancelCallback | None = None,
) -> None

This method cancels a consumer.

This does not affect already delivered messages, but it does mean the server will not send any more messages for that consumer. The client may receive an arbitrary number of messages in between sending the cancel method and receiving the cancel-ok reply. It may also be sent from the server to the client in the event of the consumer being unexpectedly cancelled (i.e. cancelled for any reason other than the server receiving the corresponding basic.cancel from the client). This allows clients to be notified of the loss of consumers due to events such as queue deletion.

A cancelled consumer's tag is retained so that a delivery already in flight when the cancel was sent is rejected rather than left unacknowledged. A cancel that expects a Basic.CancelOk retires its own entry on arrival; a nowait cancel has no reply to retire it, so its tag is kept only until _MAX_RETAINED_CANCELLED_TAGS later nowait cancels displace it (see _retain_cancelled_tag). Past that point its retention lapses: a straggling delivery for it is logged as unexpected and left unacknowledged rather than rejected, and the tag may be reused by basic_consume, so reusing the same explicit consumer_tag risks a delivery for the old consumer reaching the new one. The cap is a generous approximation of the broker's in-flight window, so this only bites under extreme nowait-cancel churn.

PARAMETER DESCRIPTION
consumer_tag

Identifier for the consumer

TYPE: str DEFAULT: ''

callback

callback(pika.frame.Method) for method Basic.CancelOk. If None, do not expect a Basic.CancelOk response, otherwise, callback must be callable

TYPE: _OnBasicCancelCallback | None DEFAULT: None

RAISES DESCRIPTION
ValueError
Source code in pika/channel.py
def basic_cancel(self,
                 consumer_tag: str = '',
                 callback: _OnBasicCancelCallback | None = None) -> None:
    """
    This method cancels a consumer.

    This does not affect already delivered messages, but it does mean the server will not send
    any more messages for that consumer. The client may receive an arbitrary number of messages
    in between sending the cancel method and receiving the cancel-ok reply. It may also be sent
    from the server to the client in the event of the consumer being unexpectedly cancelled
    (i.e. cancelled for any reason other than the server receiving the corresponding
    basic.cancel from the client). This allows clients to be notified of the loss of consumers
    due to events such as queue deletion.

    A cancelled consumer's tag is retained so that a delivery already in flight when the cancel
    was sent is rejected rather than left unacknowledged. A cancel that expects a Basic.CancelOk
    retires its own entry on arrival; a nowait cancel has no reply to retire it, so its tag is
    kept only until `_MAX_RETAINED_CANCELLED_TAGS` later nowait cancels displace it (see
    `_retain_cancelled_tag`). Past that point its retention lapses: a straggling delivery for it
    is logged as unexpected and left unacknowledged rather than rejected, and the tag may be
    reused by `basic_consume`, so reusing the same explicit consumer_tag risks a delivery for
    the old consumer reaching the new one. The cap is a generous approximation of the broker's
    in-flight window, so this only bites under extreme nowait-cancel churn.

    :param consumer_tag: Identifier for the consumer
    :param callback: callback(pika.frame.Method) for method Basic.CancelOk. If None, do not
        expect a Basic.CancelOk response, otherwise, callback must be callable
    :raises ValueError:
    """
    validators.require_string(consumer_tag, 'consumer_tag')
    self._raise_if_not_open()
    nowait = validators.rpc_completion_callback(callback)

    if consumer_tag in self._cancelled:
        # We check for cancelled first, because basic_cancel removes
        # consumers closed with nowait from self._consumers
        LOGGER.warning('basic_cancel - consumer is already cancelling: %s',
                       consumer_tag)
        return

    if consumer_tag not in self._consumers:
        # Could be cancelled by user or broker earlier
        LOGGER.warning('basic_cancel - consumer not found: %s',
                       consumer_tag)
        return

    LOGGER.debug('Cancelling consumer: %s (nowait=%s)', consumer_tag,
                 nowait)

    if nowait:
        # This is our last opportunity while the channel is open to remove
        # this consumer callback and help gc.
        del self._consumers[consumer_tag]

    if callback is not None:
        self.callbacks.add(self.channel_number, spec.Basic.CancelOk,
                           callback)

    self._cancelled.add(consumer_tag)

    if nowait:
        self._retain_cancelled_tag(consumer_tag)

    self._rpc(spec.Basic.Cancel(consumer_tag=consumer_tag, nowait=nowait),
              self._on_cancelok if not nowait else None,
              [(spec.Basic.CancelOk, {
                  'consumer_tag': consumer_tag
              })] if not nowait else [])

basic_consume

basic_consume(
    queue: str,
    on_message_callback: _OnMessageCallback,
    auto_ack: bool = False,
    exclusive: bool = False,
    consumer_tag: str | None = None,
    arguments: dict[str, Any] | None = None,
    callback: _OnBasicConsumeCallback | None = None,
) -> str

Sends the AMQP 0-9-1 command Basic.Consume to the broker and binds messages for the consumer_tag to the consumer callback. If you do not pass in a consumer_tag, one will be automatically generated for you. Returns the consumer tag.

For more information on basic_consume, see: Tutorial 2 at https://www.rabbitmq.com/getstarted.html https://www.rabbitmq.com/confirms.html https://www.rabbitmq.com/amqp-0-9-1-reference.html#basic.consume

PARAMETER DESCRIPTION
queue

The queue to consume from. Use the empty string to specify the most recent server-named queue for this channel

TYPE: str

on_message_callback

The function to call when consuming with the signature on_message_callback(channel, method, properties, body), where - channel: pika.channel.Channel - method: pika.spec.Basic.Deliver - properties: pika.spec.BasicProperties - body: bytes

TYPE: _OnMessageCallback

auto_ack

if set to True, automatic acknowledgement mode will be used (see https://www.rabbitmq.com/confirms.html). This corresponds with the 'no_ack' parameter in the basic.consume AMQP 0.9.1 method

TYPE: bool DEFAULT: False

exclusive

Don't allow other consumers on the queue

TYPE: bool DEFAULT: False

consumer_tag

Specify your own consumer tag

TYPE: str | None DEFAULT: None

arguments

Custom key/value pair arguments for the consumer

TYPE: dict[str, Any] | None DEFAULT: None

callback

callback(pika.frame.Method) for method Basic.ConsumeOk.

TYPE: _OnBasicConsumeCallback | None DEFAULT: None

RETURNS DESCRIPTION
str

Consumer tag which may be used to cancel the consumer.

RAISES DESCRIPTION
ValueError
Source code in pika/channel.py
def basic_consume(self,
                  queue: str,
                  on_message_callback: _OnMessageCallback,
                  auto_ack: bool = False,
                  exclusive: bool = False,
                  consumer_tag: str | None = None,
                  arguments: dict[str, Any] | None = None,
                  callback: _OnBasicConsumeCallback | None = None) -> str:
    """
    Sends the AMQP 0-9-1 command Basic.Consume to the broker and binds messages for the
    consumer_tag to the consumer callback. If you do not pass in a consumer_tag, one will be
    automatically generated for you. Returns the consumer tag.

    For more information on basic_consume, see:
    Tutorial 2 at https://www.rabbitmq.com/getstarted.html
    https://www.rabbitmq.com/confirms.html
    https://www.rabbitmq.com/amqp-0-9-1-reference.html#basic.consume

    :param queue: The queue to consume from. Use the empty string to
        specify the most recent server-named queue for this channel
    :param on_message_callback: The function to call when
        consuming with the signature
        on_message_callback(channel, method, properties, body), where
        - channel: pika.channel.Channel
        - method: pika.spec.Basic.Deliver
        - properties: pika.spec.BasicProperties
        - body: bytes
    :param auto_ack: if set to True, automatic acknowledgement mode
        will be used (see https://www.rabbitmq.com/confirms.html).
        This corresponds with the 'no_ack' parameter in the basic.consume
        AMQP 0.9.1 method
    :param exclusive: Don't allow other consumers on the queue
    :param consumer_tag: Specify your own consumer tag
    :param arguments: Custom key/value pair arguments for the consumer
    :param callback: callback(pika.frame.Method) for method
      Basic.ConsumeOk.
    :returns: Consumer tag which may be used to cancel the consumer.
    :raises ValueError:
    """
    validators.require_string(queue, 'queue')
    validators.require_callback(on_message_callback)
    self._raise_if_not_open()
    validators.rpc_completion_callback(callback)

    # If a consumer tag was not passed, create one
    if not consumer_tag:
        consumer_tag = self._generate_consumer_tag()

    if consumer_tag in self._consumers or consumer_tag in self._cancelled:
        raise exceptions.DuplicateConsumerTag(consumer_tag)

    if auto_ack:
        self._consumers_with_noack.add(consumer_tag)

    self._consumers[consumer_tag] = on_message_callback

    rpc_callback: Callable[
        ...,
        Any] | None = self._on_eventok if callback is None else callback

    self._rpc(
        spec.Basic.Consume(queue=queue,
                           consumer_tag=consumer_tag,
                           no_ack=auto_ack,
                           exclusive=exclusive,
                           arguments=arguments or {}), rpc_callback,
        [(spec.Basic.ConsumeOk, {
            'consumer_tag': consumer_tag
        })])

    return consumer_tag

basic_get

basic_get(
    queue: str,
    callback: _OnBasicGetCallback,
    auto_ack: bool = False,
) -> None

Get a single message from the AMQP broker.

If you want to be notified of Basic.GetEmpty, use the Channel.add_callback method adding your Basic.GetEmpty callback which should expect only one parameter, frame. Due to implementation details, this cannot be called a second time until the callback is executed. For more information on basic_get and its parameters, see:

https://www.rabbitmq.com/amqp-0-9-1-reference.html#basic.get

PARAMETER DESCRIPTION
queue

The queue from which to get a message. Use the empty string to specify the most recent server-named queue for this channel

TYPE: str

callback

The callback to call with a message that has the signature callback(channel, method, properties, body), where: - channel: pika.channel.Channel - method: pika.spec.Basic.GetOk - properties: pika.spec.BasicProperties - body: bytes

TYPE: _OnBasicGetCallback

auto_ack

Tell the broker to not expect a reply

TYPE: bool DEFAULT: False

RAISES DESCRIPTION
ValueError
Source code in pika/channel.py
def basic_get(self,
              queue: str,
              callback: _OnBasicGetCallback,
              auto_ack: bool = False) -> None:
    """
    Get a single message from the AMQP broker.

    If you want to be notified of Basic.GetEmpty, use the Channel.add_callback method
    adding your Basic.GetEmpty callback which should expect only one
    parameter, frame. Due to implementation details, this cannot be called
    a second time until the callback is executed.  For more information on
    basic_get and its parameters, see:

    https://www.rabbitmq.com/amqp-0-9-1-reference.html#basic.get

    :param queue: The queue from which to get a message. Use the empty
        string to specify the most recent server-named queue for this
        channel
    :param callback: The callback to call with a message that has
        the signature callback(channel, method, properties, body), where:
        - channel: pika.channel.Channel
        - method: pika.spec.Basic.GetOk
        - properties: pika.spec.BasicProperties
        - body: bytes
    :param auto_ack: Tell the broker to not expect a reply
    :raises ValueError:
    """
    validators.require_string(queue, 'queue')
    validators.require_callback(callback)
    if self._on_getok_callback is not None:
        raise exceptions.DuplicateGetOkCallback()
    self._on_getok_callback = callback

    # TODO Strangely, not using _rpc for the synchronous Basic.Get. Would
    # need to extend _rpc to handle Basic.GetOk method, header, and body
    # frames (or similar)
    self._send_method(spec.Basic.Get(queue=queue, no_ack=auto_ack))

basic_nack

basic_nack(
    delivery_tag: int = 0,
    multiple: bool = False,
    requeue: bool = True,
) -> None

This method allows a client to reject one or more incoming messages.

It can be used to interrupt and cancel large incoming messages, or return untreatable messages to their original queue.

PARAMETER DESCRIPTION
delivery_tag

int/long The server-assigned delivery tag

TYPE: int DEFAULT: 0

multiple

If set to True, the delivery tag is treated as "up to and including", so that multiple messages can be acknowledged with a single method. If set to False, the delivery tag refers to a single message. If the multiple field is 1, and the delivery tag is zero, this indicates acknowledgement of all outstanding messages.

TYPE: bool DEFAULT: False

requeue

If requeue is true, the server will attempt to requeue the message. If requeue is false or the requeue attempt fails the messages are discarded or dead- lettered.

TYPE: bool DEFAULT: True

Source code in pika/channel.py
def basic_nack(self,
               delivery_tag: int = 0,
               multiple: bool = False,
               requeue: bool = True) -> None:
    """
    This method allows a client to reject one or more incoming messages.

    It can be used to interrupt and cancel large incoming messages, or return untreatable
    messages to their original queue.

    :param delivery_tag: int/long The server-assigned delivery tag
    :param multiple: If set to True, the delivery tag is treated as "up to and including", so
        that multiple messages can be acknowledged with a single method. If set to False, the
        delivery tag refers to a single message. If the multiple field is 1, and the delivery
        tag is zero, this indicates acknowledgement of all outstanding messages.
    :param requeue: If requeue is true, the server will attempt to requeue the message. If
        requeue is false or the requeue attempt fails the messages are discarded or dead-
        lettered.
    """
    self._raise_if_not_open()
    return self._send_method(
        spec.Basic.Nack(delivery_tag, multiple, requeue))

basic_publish

basic_publish(
    exchange: str,
    routing_key: str,
    body: bytes,
    properties: BasicProperties | None = None,
    mandatory: bool = False,
) -> None

Publish to the channel with the given exchange, routing key and body.

For more information on basic_publish and what the parameters do, see:

https://www.rabbitmq.com/amqp-0-9-1-reference.html#basic.publish

PARAMETER DESCRIPTION
exchange

The exchange to publish to

TYPE: str

routing_key

The routing key to bind on

TYPE: str

body

The message body

TYPE: bytes

properties

Basic.properties

TYPE: BasicProperties | None DEFAULT: None

mandatory

The mandatory flag

TYPE: bool DEFAULT: False

Source code in pika/channel.py
def basic_publish(self,
                  exchange: str,
                  routing_key: str,
                  body: bytes,
                  properties: spec.BasicProperties | None = None,
                  mandatory: bool = False) -> None:
    """
    Publish to the channel with the given exchange, routing key and body.

    For more information on basic_publish and what the parameters do, see:

    https://www.rabbitmq.com/amqp-0-9-1-reference.html#basic.publish

    :param exchange: The exchange to publish to
    :param routing_key: The routing key to bind on
    :param body: The message body
    :param properties: Basic.properties
    :param mandatory: The mandatory flag
    """
    self._raise_if_not_open()
    body = as_bytes(body)
    properties = properties or spec.BasicProperties()
    self._send_method(
        spec.Basic.Publish(exchange=exchange,
                           routing_key=routing_key,
                           mandatory=mandatory), (properties, body))

basic_qos

basic_qos(
    prefetch_size: int = 0,
    prefetch_count: int = 0,
    global_qos: bool = False,
    callback: _OnBasicQosCallback | None = None,
) -> None

Specify quality of service.

This method requests a specific quality of service. The client can request that messages 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. The QoS can be applied separately to each new consumer on channel or shared across all consumers on the channel. Prefetching gives a performance improvement.

PARAMETER DESCRIPTION
prefetch_size

This field specifies the prefetch window size. 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 into other prefetch limits). May be set to zero, meaning "no specific limit", although other prefetch limits may still apply. The prefetch-size is ignored by consumers who have enabled the no-ack option.

TYPE: int DEFAULT: 0

prefetch_count

Specifies a prefetch window in terms of whole messages. This field may be used in combination with the prefetch-size field; a message will only be sent in advance if both prefetch windows (and those at the channel and connection level) allow it. The prefetch-count is ignored by consumers who have enabled the no-ack option.

TYPE: int DEFAULT: 0

global_qos

Should the QoS be shared across all consumers on the channel.

TYPE: bool DEFAULT: False

callback

The callback to call for Basic.QosOk response

TYPE: _OnBasicQosCallback | None DEFAULT: None

RETURNS DESCRIPTION
None

None. Method frame from the Basic.Qos-ok response is delivered to callback when provided.

RAISES DESCRIPTION
ValueError
Source code in pika/channel.py
def basic_qos(self,
              prefetch_size: int = 0,
              prefetch_count: int = 0,
              global_qos: bool = False,
              callback: _OnBasicQosCallback | None = None) -> None:
    """
    Specify quality of service.

    This method requests a specific quality of service. The client can request that messages 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. The QoS can be
    applied separately to each new consumer on channel or shared across all consumers on the
    channel. Prefetching gives a performance improvement.

    :param prefetch_size: This field specifies the prefetch window size. 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 into other prefetch limits). May be set to zero, meaning "no specific
        limit", although other prefetch limits may still apply. The prefetch-size is ignored by
        consumers who have enabled the no-ack option.
    :param prefetch_count: Specifies a prefetch window in terms of whole messages. This field
        may be used in combination with the prefetch-size field; a message will only be sent in
        advance if both prefetch windows (and those at the channel and connection level) allow
        it. The prefetch-count is ignored by consumers who have enabled the no-ack option.
    :param global_qos: Should the QoS be shared across all consumers on the channel.
    :param callback: The callback to call for Basic.QosOk response
    :returns:``None``. Method frame from the Basic.Qos-ok response is delivered to ``callback``
        when provided.
    :raises ValueError:
    """
    self._raise_if_not_open()
    validators.rpc_completion_callback(callback)
    validators.zero_or_greater('prefetch_size', prefetch_size)
    validators.zero_or_greater('prefetch_count', prefetch_count)
    return self._rpc(
        spec.Basic.Qos(prefetch_size, prefetch_count, global_qos), callback,
        [spec.Basic.QosOk])

basic_recover

basic_recover(
    requeue: bool = False,
    callback: _OnBasicRecoverCallback | None = None,
) -> None

This method asks the server to redeliver all unacknowledged messages on a specified channel. Zero or more messages may be redelivered. This method replaces the asynchronous Recover.

PARAMETER DESCRIPTION
requeue

If False, the message will be redelivered to the original recipient. If True, the server will attempt to requeue the message, potentially then delivering it to an alternative subscriber.

TYPE: bool DEFAULT: False

callback

callback(pika.frame.Method) for method Basic.RecoverOk

TYPE: _OnBasicRecoverCallback | None DEFAULT: None

RETURNS DESCRIPTION
None

None. Method frame from the Basic.Recover-ok response is delivered to callback when provided.

RAISES DESCRIPTION
ValueError
Source code in pika/channel.py
def basic_recover(self,
                  requeue: bool = False,
                  callback: _OnBasicRecoverCallback | None = None) -> None:
    """
    This method asks the server to redeliver all unacknowledged messages on a specified channel.
    Zero or more messages may be redelivered. This method replaces the asynchronous Recover.

    :param requeue: If False, the message will be redelivered to the original recipient. If
        True, the server will attempt to requeue the message, potentially then delivering it to
        an alternative subscriber.
    :param callback: callback(pika.frame.Method) for method Basic.RecoverOk
    :returns:``None``. Method frame from the Basic.Recover-ok response is delivered to
        ``callback`` when provided.
    :raises ValueError:
    """
    self._raise_if_not_open()
    validators.rpc_completion_callback(callback)
    return self._rpc(spec.Basic.Recover(requeue), callback,
                     [spec.Basic.RecoverOk])

basic_reject

basic_reject(
    delivery_tag: int = 0, requeue: bool = True
) -> None

Reject an incoming message.

This method allows a client to reject a message. It can be used to interrupt and cancel large incoming messages, or return untreatable messages to their original queue.

PARAMETER DESCRIPTION
delivery_tag

int/long The server-assigned delivery tag

TYPE: int DEFAULT: 0

requeue

If requeue is true, the server will attempt to requeue the message. If requeue is false or the requeue attempt fails the messages are discarded or dead- lettered.

TYPE: bool DEFAULT: True

RAISES DESCRIPTION
TypeError
Source code in pika/channel.py
def basic_reject(self, delivery_tag: int = 0, requeue: bool = True) -> None:
    """
    Reject an incoming message.

    This method allows a client to reject a message. It can be used to interrupt and cancel
    large incoming messages, or return untreatable messages to their original queue.

    :param delivery_tag: int/long The server-assigned delivery tag
    :param requeue: If requeue is true, the server will attempt to requeue the message. If
        requeue is false or the requeue attempt fails the messages are discarded or dead-
        lettered.
    :raises TypeError:
    """
    self._raise_if_not_open()
    if not isinstance(delivery_tag, int):
        raise TypeError('delivery_tag must be an integer')
    return self._send_method(spec.Basic.Reject(delivery_tag, requeue))

close

close(
    reply_code: int = 0, reply_text: str = 'Normal shutdown'
) -> None

Invoke a graceful shutdown of the channel with the AMQP Broker.

If channel is OPENING, transition to CLOSING and suppress the incoming Channel.OpenOk, if any.

PARAMETER DESCRIPTION
reply_code

The reason code to send to broker

TYPE: int DEFAULT: 0

reply_text

The reason text to send to broker

TYPE: str DEFAULT: 'Normal shutdown'

RAISES DESCRIPTION
ChannelWrongStateError

if channel is closed or closing

Source code in pika/channel.py
def close(self,
          reply_code: int = 0,
          reply_text: str = 'Normal shutdown') -> None:
    """
    Invoke a graceful shutdown of the channel with the AMQP Broker.

    If channel is OPENING, transition to CLOSING and suppress the incoming Channel.OpenOk, if
    any.

    :param reply_code: The reason code to send to broker
    :param reply_text: The reason text to send to broker
    :raises ChannelWrongStateError: if channel is closed or closing
    """
    if self.is_closed or self.is_closing:
        # Whoever is calling `close` might expect the on-channel-close-cb
        # to be called, which won't happen when it's already closed.
        self._raise_if_not_open()

    # If channel is OPENING, we will transition it to CLOSING state,
    # causing the _on_openok method to suppress the OPEN state transition
    # and the on-channel-open-callback

    LOGGER.info('Closing channel (%s): %r on %s', reply_code, reply_text,
                self)

    # Save the reason info so that we may use it in the '_on_channel_close'
    # callback processing
    self._closing_reason = exceptions.ChannelClosedByClient(
        reply_code, reply_text)

    for consumer_tag in list(self._consumers.keys()):
        if consumer_tag not in self._cancelled:
            self.basic_cancel(consumer_tag=consumer_tag)

    # Change state after cancelling consumers to avoid
    # ChannelWrongStateError exception from basic_cancel
    self._set_state(self.CLOSING)

    self._rpc(spec.Channel.Close(reply_code, reply_text, 0, 0),
              self._on_closeok, [spec.Channel.CloseOk])

confirm_delivery

confirm_delivery(
    ack_nack_callback: _OnAckNackCallback,
    callback: _OnConfirmDeliveryCallback | None = None,
) -> None

Turn on Confirm mode in the channel.

Pass in a callback to be notified by the Broker when a message has been confirmed as received or rejected (Basic.Ack, Basic.Nack) from the broker to the publisher.

For more information see: https://www.rabbitmq.com/confirms.html

PARAMETER DESCRIPTION
ack_nack_callback

Required callback for delivery confirmations that has the following signature: callback(pika.frame.Method), where method_frame contains either method spec.Basic.Ack or spec.Basic.Nack.

TYPE: _OnAckNackCallback

callback

callback(pika.frame.Method) for method Confirm.SelectOk

TYPE: _OnConfirmDeliveryCallback | None DEFAULT: None

RAISES DESCRIPTION
TypeError

if ack_nack_callback is not callable

.. note:: Calling this method more than once on the same channel replaces the previously registered ack_nack_callback rather than adding an additional one. Only the most recently registered callback receives Basic.Ack/Basic.Nack notifications.

Source code in pika/channel.py
def confirm_delivery(
        self,
        ack_nack_callback: _OnAckNackCallback,
        callback: _OnConfirmDeliveryCallback | None = None) -> None:
    """
    Turn on Confirm mode in the channel.

    Pass in a callback to be notified by the Broker when a message has been confirmed as received or
    rejected (Basic.Ack, Basic.Nack) from the broker to the publisher.

    For more information see:
        https://www.rabbitmq.com/confirms.html

    :param ack_nack_callback: Required callback for delivery
        confirmations that has the following signature:
        callback(pika.frame.Method), where method_frame contains
        either method `spec.Basic.Ack` or `spec.Basic.Nack`.
    :param callback: callback(pika.frame.Method) for method
        Confirm.SelectOk
    :raises TypeError: if `ack_nack_callback` is not callable

    .. note::
        Calling this method more than once on the same channel replaces
        the previously registered ``ack_nack_callback`` rather than adding
        an additional one. Only the most recently registered callback
        receives ``Basic.Ack``/``Basic.Nack`` notifications.
    """
    if not callable(ack_nack_callback):
        # confirm_deliver requires a callback; it's meaningless
        # without a user callback to receive Basic.Ack/Basic.Nack notifications
        raise TypeError('confirm_delivery requires a callback '
                        'to receive Basic.Ack/Basic.Nack notifications')

    self._raise_if_not_open()
    nowait = validators.rpc_completion_callback(callback)

    if not (self.connection.publisher_confirms and
            self.connection.basic_nack):
        raise exceptions.MethodNotImplemented(
            'Confirm.Select not Supported by Server')

    # Replace any previously registered ack/nack callback so repeated
    # calls don't stack listeners and fire stale callbacks (see #1602).
    if self._on_ack_nack_callback is not None:
        self.callbacks.remove(self.channel_number, spec.Basic.Ack,
                              self._on_ack_nack_callback)
        self.callbacks.remove(self.channel_number, spec.Basic.Nack,
                              self._on_ack_nack_callback)

    # Add the ack and nack callback
    self.callbacks.add(self.channel_number, spec.Basic.Ack,
                       ack_nack_callback, False)
    self.callbacks.add(self.channel_number, spec.Basic.Nack,
                       ack_nack_callback, False)
    self._on_ack_nack_callback = ack_nack_callback

    self._rpc(spec.Confirm.Select(nowait), callback,
              [spec.Confirm.SelectOk] if not nowait else [])

exchange_bind

exchange_bind(
    destination: str,
    source: str,
    routing_key: str = '',
    arguments: dict[str, Any] | None = None,
    callback: _OnExchangeBindCallback | None = None,
) -> None

Bind an exchange to another exchange.

PARAMETER DESCRIPTION
destination

The destination exchange to bind

TYPE: str

source

The source exchange to bind to

TYPE: str

routing_key

The routing key to bind on

TYPE: str DEFAULT: ''

arguments

Custom key/value pair arguments for the binding

TYPE: dict[str, Any] | None DEFAULT: None

callback

callback(pika.frame.Method) for method Exchange.BindOk

TYPE: _OnExchangeBindCallback | None DEFAULT: None

RETURNS DESCRIPTION
None

None. Method frame from the Exchange.Bind-ok response is delivered to callback when synchronous (no ok frame in nowait mode).

RAISES DESCRIPTION
ValueError
Source code in pika/channel.py
def exchange_bind(self,
                  destination: str,
                  source: str,
                  routing_key: str = '',
                  arguments: dict[str, Any] | None = None,
                  callback: _OnExchangeBindCallback | None = None) -> None:
    """
    Bind an exchange to another exchange.

    :param destination: The destination exchange to bind
    :param source: The source exchange to bind to
    :param routing_key: The routing key to bind on
    :param arguments: Custom key/value pair arguments for the binding
    :param callback: callback(pika.frame.Method) for method Exchange.BindOk
    :returns:``None``. Method frame from the Exchange.Bind-ok response is delivered to
        ``callback`` when synchronous (no ok frame in nowait mode).
    :raises ValueError:
    """
    self._raise_if_not_open()
    validators.require_string(destination, 'destination')
    validators.require_string(source, 'source')
    nowait = validators.rpc_completion_callback(callback)
    return self._rpc(
        spec.Exchange.Bind(0, destination, source, routing_key, nowait,
                           arguments or {}), callback,
        [spec.Exchange.BindOk] if not nowait else [])

exchange_declare

exchange_declare(
    exchange: str,
    exchange_type: str = direct,
    passive: bool = False,
    durable: bool = False,
    auto_delete: bool = False,
    internal: bool = False,
    arguments: dict[str, Any] | None = None,
    callback: _OnExchangeDeclareCallback | None = None,
) -> None

This method creates an exchange if it does not already exist, and if the exchange exists, verifies that it is of the correct and expected class.

If passive set, the server will reply with Declare-Ok if the exchange already exists with the same name, and raise an error if not and if the exchange does not already exist, the server MUST raise a channel exception with reply code 404 (not found).

PARAMETER DESCRIPTION
exchange

The exchange name consists of a non-empty sequence of these characters: letters, digits, hyphen, underscore, period, or colon

TYPE: str

exchange_type

The exchange type to use

TYPE: str DEFAULT: direct

passive

Perform a declare or just check to see if it exists

TYPE: bool DEFAULT: False

durable

Survive a reboot of RabbitMQ

TYPE: bool DEFAULT: False

auto_delete

Remove when no more queues are bound to it

TYPE: bool DEFAULT: False

internal

Can only be published to by other exchanges

TYPE: bool DEFAULT: False

arguments

Custom key/value pair arguments for the exchange

TYPE: dict[str, Any] | None DEFAULT: None

callback

callback(pika.frame.Method) for method Exchange.DeclareOk

TYPE: _OnExchangeDeclareCallback | None DEFAULT: None

RETURNS DESCRIPTION
None

None. Method frame from the Exchange.Declare-ok response is delivered to callback when synchronous (no ok frame in nowait mode).

RAISES DESCRIPTION
ValueError
Source code in pika/channel.py
def exchange_declare(
        self,
        exchange: str,
        exchange_type: str = ExchangeType.direct,
        passive: bool = False,
        durable: bool = False,
        auto_delete: bool = False,
        internal: bool = False,
        arguments: dict[str, Any] | None = None,
        callback: _OnExchangeDeclareCallback | None = None) -> None:
    """
    This method creates an exchange if it does not already exist, and if the exchange exists,
    verifies that it is of the correct and expected class.

    If passive set, the server will reply with Declare-Ok if the exchange
    already exists with the same name, and raise an error if not and if the
    exchange does not already exist, the server MUST raise a channel
    exception with reply code 404 (not found).

    :param exchange: The exchange name consists of a non-empty sequence
        of these characters: letters, digits, hyphen, underscore, period,
        or colon
    :param exchange_type: The exchange type to use
    :param passive: Perform a declare or just check to see if it exists
    :param durable: Survive a reboot of RabbitMQ
    :param auto_delete: Remove when no more queues are bound to it
    :param internal: Can only be published to by other exchanges
    :param arguments: Custom key/value pair arguments for the exchange
    :param callback: callback(pika.frame.Method) for method Exchange.DeclareOk
    :returns: ``None``. Method frame from the Exchange.Declare-ok response is
        delivered to ``callback`` when synchronous (no ok frame in nowait
        mode).
    :raises ValueError:
    """
    validators.require_string(exchange, 'exchange')
    self._raise_if_not_open()
    nowait = validators.rpc_completion_callback(callback)
    if isinstance(exchange_type, Enum):
        exchange_type = exchange_type.value
    return self._rpc(
        spec.Exchange.Declare(0, exchange, exchange_type, passive, durable,
                              auto_delete, internal, nowait, arguments or
                              {}), callback,
        [spec.Exchange.DeclareOk] if not nowait else [])

exchange_delete

exchange_delete(
    exchange: str | None = None,
    if_unused: bool = False,
    callback: _OnExchangeDeleteCallback | None = None,
) -> None

Delete the exchange.

PARAMETER DESCRIPTION
exchange

The exchange name

TYPE: str | None DEFAULT: None

if_unused

only delete if the exchange is unused

TYPE: bool DEFAULT: False

callback

callback(pika.frame.Method) for method Exchange.DeleteOk

TYPE: _OnExchangeDeleteCallback | None DEFAULT: None

RETURNS DESCRIPTION
None

None. Method frame from the Exchange.Delete-ok response is delivered to callback when synchronous (no ok frame in nowait mode).

RAISES DESCRIPTION
ValueError
Source code in pika/channel.py
def exchange_delete(
        self,
        exchange: str | None = None,
        if_unused: bool = False,
        callback: _OnExchangeDeleteCallback | None = None) -> None:
    """
    Delete the exchange.

    :param exchange: The exchange name
    :param if_unused: only delete if the exchange is unused
    :param callback: callback(pika.frame.Method) for method Exchange.DeleteOk
    :returns:``None``. Method frame from the Exchange.Delete-ok response is delivered to
        ``callback`` when synchronous (no ok frame in nowait mode).
    :raises ValueError:
    """
    self._raise_if_not_open()
    nowait = validators.rpc_completion_callback(callback)
    return self._rpc(spec.Exchange.Delete(0, exchange, if_unused,
                                          nowait), callback,
                     [spec.Exchange.DeleteOk] if not nowait else [])

exchange_unbind

exchange_unbind(
    destination: str | None = None,
    source: str | None = None,
    routing_key: str = '',
    arguments: dict[str, Any] | None = None,
    callback: _OnExchangeUnbindCallback | None = None,
) -> None

Unbind an exchange from another exchange.

PARAMETER DESCRIPTION
destination

The destination exchange to unbind

TYPE: str | None DEFAULT: None

source

The source exchange to unbind from

TYPE: str | None DEFAULT: None

routing_key

The routing key to unbind

TYPE: str DEFAULT: ''

arguments

Custom key/value pair arguments for the binding

TYPE: dict[str, Any] | None DEFAULT: None

callback

callback(pika.frame.Method) for method Exchange.UnbindOk

TYPE: _OnExchangeUnbindCallback | None DEFAULT: None

RETURNS DESCRIPTION
None

None. Method frame from the Exchange.Unbind-ok response is delivered to callback when synchronous (no ok frame in nowait mode).

RAISES DESCRIPTION
ValueError
Source code in pika/channel.py
def exchange_unbind(
        self,
        destination: str | None = None,
        source: str | None = None,
        routing_key: str = '',
        arguments: dict[str, Any] | None = None,
        callback: _OnExchangeUnbindCallback | None = None) -> None:
    """
    Unbind an exchange from another exchange.

    :param destination: The destination exchange to unbind
    :param source: The source exchange to unbind from
    :param routing_key: The routing key to unbind
    :param arguments: Custom key/value pair arguments for the binding
    :param callback: callback(pika.frame.Method) for method Exchange.UnbindOk
    :returns:``None``. Method frame from the Exchange.Unbind-ok response is delivered to
        ``callback`` when synchronous (no ok frame in nowait mode).
    :raises ValueError:
    """
    self._raise_if_not_open()
    nowait = validators.rpc_completion_callback(callback)
    return self._rpc(
        spec.Exchange.Unbind(0, destination, source, routing_key, nowait,
                             arguments), callback,
        [spec.Exchange.UnbindOk] if not nowait else [])

flow

flow(
    active: bool, callback: _OnFlowCallback | None = None
) -> None

Turn Channel flow control off and on.

Pass a callback to be notified of the response from the server. active is a bool. Callback should expect a bool in response indicating channel flow state. For more information, please reference:

https://www.rabbitmq.com/amqp-0-9-1-reference.html#channel.flow

PARAMETER DESCRIPTION
active

Turn flow on or off

TYPE: bool

callback

callback(bool) upon completion

TYPE: _OnFlowCallback | None DEFAULT: None

RAISES DESCRIPTION
ValueError
Source code in pika/channel.py
def flow(self,
         active: bool,
         callback: _OnFlowCallback | None = None) -> None:
    """
    Turn Channel flow control off and on.

    Pass a callback to be notified of the response from the server. active is a bool. Callback
    should expect a bool in response indicating channel flow state. For more information, please
    reference:

    https://www.rabbitmq.com/amqp-0-9-1-reference.html#channel.flow

    :param active: Turn flow on or off
    :param callback: callback(bool) upon completion
    :raises ValueError:
    """
    self._raise_if_not_open()
    validators.rpc_completion_callback(callback)
    self._on_flowok_callback = callback
    self._rpc(spec.Channel.Flow(active), self._on_flowok,
              [spec.Channel.FlowOk])

open

open() -> None

Open the channel.

Source code in pika/channel.py
def open(self) -> None:
    """Open the channel."""
    self._set_state(self.OPENING)
    self._add_callbacks()
    self._rpc(spec.Channel.Open(), self._on_openok, [spec.Channel.OpenOk])

queue_bind

queue_bind(
    queue: str,
    exchange: str,
    routing_key: str | None = None,
    arguments: dict[str, Any] | None = None,
    callback: _OnQueueBindCallback | None = None,
) -> None

Bind the queue to the specified exchange.

PARAMETER DESCRIPTION
queue

The queue to bind to the exchange

TYPE: str

exchange

The source exchange to bind to

TYPE: str

routing_key

The routing key to bind on

TYPE: str | None DEFAULT: None

arguments

Custom key/value pair arguments for the binding

TYPE: dict[str, Any] | None DEFAULT: None

callback

callback(pika.frame.Method) for method Queue.BindOk

TYPE: _OnQueueBindCallback | None DEFAULT: None

RETURNS DESCRIPTION
None

None. Method frame from the Queue.Bind-ok response is delivered to callback when synchronous (no ok frame in nowait mode).

RAISES DESCRIPTION
ValueError
Source code in pika/channel.py
def queue_bind(self,
               queue: str,
               exchange: str,
               routing_key: str | None = None,
               arguments: dict[str, Any] | None = None,
               callback: _OnQueueBindCallback | None = None) -> None:
    """
    Bind the queue to the specified exchange.

    :param queue: The queue to bind to the exchange
    :param exchange: The source exchange to bind to
    :param routing_key: The routing key to bind on
    :param arguments: Custom key/value pair arguments for the binding
    :param callback: callback(pika.frame.Method) for method Queue.BindOk
    :returns:``None``. Method frame from the Queue.Bind-ok response is delivered to ``callback``
        when synchronous (no ok frame in nowait mode).
    :raises ValueError:
    """
    validators.require_string(queue, 'queue')
    validators.require_string(exchange, 'exchange')
    self._raise_if_not_open()
    nowait = validators.rpc_completion_callback(callback)
    if routing_key is None:
        routing_key = queue
    return self._rpc(
        spec.Queue.Bind(0, queue, exchange, routing_key, nowait,
                        arguments or {}), callback,
        [spec.Queue.BindOk] if not nowait else [])

queue_declare

queue_declare(
    queue: str,
    passive: bool = False,
    durable: bool = False,
    exclusive: bool = False,
    auto_delete: bool = False,
    arguments: dict[str, Any] | None = None,
    callback: _OnQueueDeclareCallback | None = None,
) -> None

Declare queue, create if needed.

This method creates or checks a queue. When creating a new queue the client can specify various properties that control the durability of the queue and its contents, and the level of sharing for the queue.

Use an empty string as the queue name for the broker to auto-generate one

PARAMETER DESCRIPTION
queue

The queue name; if empty string, the broker will create a unique queue name

TYPE: str

passive

Only check to see if the queue exists

TYPE: bool DEFAULT: False

durable

Survive reboots of the broker

TYPE: bool DEFAULT: False

exclusive

Only allow access by the current connection

TYPE: bool DEFAULT: False

auto_delete

Delete after consumer cancels or disconnects

TYPE: bool DEFAULT: False

arguments

Custom key/value arguments for the queue

TYPE: dict[str, Any] | None DEFAULT: None

callback

callback(pika.frame.Method) for method Queue.DeclareOk

TYPE: _OnQueueDeclareCallback | None DEFAULT: None

RETURNS DESCRIPTION
None

None. Method frame from the Queue.Declare-ok response is delivered to callback when synchronous (no ok frame in nowait mode).

RAISES DESCRIPTION
ValueError
Source code in pika/channel.py
def queue_declare(self,
                  queue: str,
                  passive: bool = False,
                  durable: bool = False,
                  exclusive: bool = False,
                  auto_delete: bool = False,
                  arguments: dict[str, Any] | None = None,
                  callback: _OnQueueDeclareCallback | None = None) -> None:
    """
    Declare queue, create if needed.

    This method creates or checks a queue. When creating a new queue the client can specify various
    properties that control the durability of the queue and its contents,
    and the level of sharing for the queue.

    Use an empty string as the queue name for the broker to auto-generate
    one

    :param queue: The queue name; if empty string, the broker will
        create a unique queue name
    :param passive: Only check to see if the queue exists
    :param durable: Survive reboots of the broker
    :param exclusive: Only allow access by the current connection
    :param auto_delete: Delete after consumer cancels or disconnects
    :param arguments: Custom key/value arguments for the queue
    :param callback: callback(pika.frame.Method) for method Queue.DeclareOk
    :returns: ``None``. Method frame from the Queue.Declare-ok response is
        delivered to ``callback`` when synchronous (no ok frame in nowait
        mode).
    :raises ValueError:
    """
    validators.require_string(queue, 'queue')
    self._raise_if_not_open()
    nowait = validators.rpc_completion_callback(callback)

    condition: Any
    if queue:
        condition = (spec.Queue.DeclareOk, {'queue': queue})
    else:
        condition = spec.Queue.DeclareOk
    replies = [condition] if not nowait else []

    return self._rpc(
        spec.Queue.Declare(0, queue, passive, durable, exclusive,
                           auto_delete, nowait, arguments or {}), callback,
        replies)

queue_delete

queue_delete(
    queue: str,
    if_unused: bool = False,
    if_empty: bool = False,
    callback: _OnQueueDeleteCallback | None = None,
) -> None

Delete a queue from the broker.

PARAMETER DESCRIPTION
queue

The queue to delete

TYPE: str

if_unused

only delete if it's unused

TYPE: bool DEFAULT: False

if_empty

only delete if the queue is empty

TYPE: bool DEFAULT: False

callback

callback(pika.frame.Method) for method Queue.DeleteOk

TYPE: _OnQueueDeleteCallback | None DEFAULT: None

RETURNS DESCRIPTION
None

None. Method frame from the Queue.Delete-ok response is delivered to callback when synchronous (no ok frame in nowait mode).

RAISES DESCRIPTION
ValueError
Source code in pika/channel.py
def queue_delete(self,
                 queue: str,
                 if_unused: bool = False,
                 if_empty: bool = False,
                 callback: _OnQueueDeleteCallback | None = None) -> None:
    """
    Delete a queue from the broker.

    :param queue: The queue to delete
    :param if_unused: only delete if it's unused
    :param if_empty: only delete if the queue is empty
    :param callback: callback(pika.frame.Method) for method Queue.DeleteOk
    :returns:``None``. Method frame from the Queue.Delete-ok response is delivered to
        ``callback`` when synchronous (no ok frame in nowait mode).
    :raises ValueError:
    """
    self._raise_if_not_open()
    validators.require_string(queue, 'queue')
    nowait = validators.rpc_completion_callback(callback)
    replies = [spec.Queue.DeleteOk] if not nowait else []
    return self._rpc(
        spec.Queue.Delete(0, queue, if_unused, if_empty, nowait), callback,
        replies)

queue_purge

queue_purge(
    queue: str,
    callback: _OnQueuePurgeCallback | None = None,
) -> None

Purge all of the messages from the specified queue.

PARAMETER DESCRIPTION
queue

The queue to purge

TYPE: str

callback

callback(pika.frame.Method) for method Queue.PurgeOk

TYPE: _OnQueuePurgeCallback | None DEFAULT: None

RETURNS DESCRIPTION
None

None. Method frame from the Queue.Purge-ok response is delivered to callback when synchronous (no ok frame in nowait mode).

RAISES DESCRIPTION
ValueError
Source code in pika/channel.py
def queue_purge(self,
                queue: str,
                callback: _OnQueuePurgeCallback | None = None) -> None:
    """
    Purge all of the messages from the specified queue.

    :param queue: The queue to purge
    :param callback: callback(pika.frame.Method) for method Queue.PurgeOk
    :returns:``None``. Method frame from the Queue.Purge-ok response is delivered to
        ``callback`` when synchronous (no ok frame in nowait mode).
    :raises ValueError:
    """
    self._raise_if_not_open()
    validators.require_string(queue, 'queue')
    nowait = validators.rpc_completion_callback(callback)
    replies = [spec.Queue.PurgeOk] if not nowait else []
    return self._rpc(spec.Queue.Purge(0, queue, nowait), callback, replies)

queue_unbind

queue_unbind(
    queue: str,
    exchange: str | None = None,
    routing_key: str | None = None,
    arguments: dict[str, Any] | None = None,
    callback: _OnQueueUnbindCallback | None = None,
) -> None

Unbind a queue from an exchange.

PARAMETER DESCRIPTION
queue

The queue to unbind from the exchange

TYPE: str

exchange

The source exchange to bind from

TYPE: str | None DEFAULT: None

routing_key

The routing key to unbind

TYPE: str | None DEFAULT: None

arguments

Custom key/value pair arguments for the binding

TYPE: dict[str, Any] | None DEFAULT: None

callback

callback(pika.frame.Method) for method Queue.UnbindOk

TYPE: _OnQueueUnbindCallback | None DEFAULT: None

RETURNS DESCRIPTION
None

None. Method frame from the Queue.Unbind-ok response is delivered to callback when provided.

RAISES DESCRIPTION
ValueError
Source code in pika/channel.py
def queue_unbind(self,
                 queue: str,
                 exchange: str | None = None,
                 routing_key: str | None = None,
                 arguments: dict[str, Any] | None = None,
                 callback: _OnQueueUnbindCallback | None = None) -> None:
    """
    Unbind a queue from an exchange.

    :param queue: The queue to unbind from the exchange
    :param exchange: The source exchange to bind from
    :param routing_key: The routing key to unbind
    :param arguments: Custom key/value pair arguments for the binding
    :param callback: callback(pika.frame.Method) for method Queue.UnbindOk
    :returns:``None``. Method frame from the Queue.Unbind-ok response is delivered to
        ``callback`` when provided.
    :raises ValueError:
    """
    self._raise_if_not_open()
    validators.require_string(queue, 'queue')
    validators.rpc_completion_callback(callback)
    if routing_key is None:
        routing_key = queue
    return self._rpc(
        spec.Queue.Unbind(0, queue, exchange, routing_key, arguments or {}),
        callback, [spec.Queue.UnbindOk])

remove_callback

remove_callback(
    callback: Callable[..., Any],
    replies: Sequence[type[Method]] | None = None,
) -> bool

Remove a callback previously registered via :meth:add_callback.

Mirrors :meth:add_callback: the callback is matched by identity and removed from each reply key it is registered under. If replies is None, the callback is removed from every reply key it is currently registered under.

PARAMETER DESCRIPTION
callback

The callback to remove

TYPE: Callable[..., Any]

replies

The replies to remove the callback from, or None to remove it from every reply key it is registered under

TYPE: Sequence[type[Method]] | None DEFAULT: None

RETURNS DESCRIPTION
bool

True if at least one matching callback was removed

Source code in pika/channel.py
def remove_callback(
        self,
        callback: Callable[..., Any],
        replies: Sequence[type[amqp_object.Method]] | None = None) -> bool:
    """
    Remove a callback previously registered via :meth:`add_callback`.

    Mirrors :meth:`add_callback`: the callback is matched by identity and removed
    from each reply key it is registered under. If ``replies`` is ``None``, the
    callback is removed from every reply key it is currently registered under.

    :param callback: The callback to remove
    :param replies: The replies to remove the callback from, or ``None`` to
        remove it from every reply key it is registered under
    :returns: ``True`` if at least one matching callback was removed
    """
    reply_keys = (self.callbacks.keys(self.channel_number)
                  if replies is None else replies)
    removed = False
    for reply in reply_keys:
        if self.callbacks.remove_matching(self.channel_number, reply,
                                          lambda cb: cb == callback):
            removed = True
    return removed

remove_on_cancel_callback

remove_on_cancel_callback(
    callback: _OnCancelCallback,
) -> bool

Remove a callback registered via :meth:add_on_cancel_callback.

PARAMETER DESCRIPTION
callback

The callback to remove

TYPE: _OnCancelCallback

RETURNS DESCRIPTION
bool

True if the callback was removed, False if it was absent

Source code in pika/channel.py
def remove_on_cancel_callback(self, callback: _OnCancelCallback) -> bool:
    """
    Remove a callback registered via :meth:`add_on_cancel_callback`.

    :param callback: The callback to remove
    :returns:``True`` if the callback was removed, ``False`` if it was absent
    """
    return self.callbacks.remove_matching(self.channel_number,
                                          spec.Basic.Cancel,
                                          lambda cb: cb == callback)

remove_on_close_callback

remove_on_close_callback(
    callback: _OnCloseCallback,
) -> bool

Remove a callback registered via :meth:add_on_close_callback.

PARAMETER DESCRIPTION
callback

The callback to remove

TYPE: _OnCloseCallback

RETURNS DESCRIPTION
bool

True if the callback was removed, False if it was absent

Source code in pika/channel.py
def remove_on_close_callback(self, callback: _OnCloseCallback) -> bool:
    """
    Remove a callback registered via :meth:`add_on_close_callback`.

    :param callback: The callback to remove
    :returns:``True`` if the callback was removed, ``False`` if it was absent
    """
    return self.callbacks.remove_matching(self.channel_number,
                                          '_on_channel_close',
                                          lambda cb: cb == callback)

remove_on_flow_callback

remove_on_flow_callback(callback: _OnFlowCallback) -> bool

Remove a callback registered via :meth:add_on_flow_callback.

PARAMETER DESCRIPTION
callback

The callback to remove

TYPE: _OnFlowCallback

RETURNS DESCRIPTION
bool

True if the callback was removed, False if it was absent

Source code in pika/channel.py
def remove_on_flow_callback(self, callback: _OnFlowCallback) -> bool:
    """
    Remove a callback registered via :meth:`add_on_flow_callback`.

    :param callback: The callback to remove
    :returns:``True`` if the callback was removed, ``False`` if it was absent
    """
    return self.callbacks.remove_matching(self.channel_number,
                                          spec.Channel.Flow,
                                          lambda cb: cb == callback)

remove_on_return_callback

remove_on_return_callback(
    callback: _OnReturnCallback,
) -> bool

Remove a callback registered via :meth:add_on_return_callback.

PARAMETER DESCRIPTION
callback

The callback to remove

TYPE: _OnReturnCallback

RETURNS DESCRIPTION
bool

True if the callback was removed, False if it was absent

Source code in pika/channel.py
def remove_on_return_callback(self, callback: _OnReturnCallback) -> bool:
    """
    Remove a callback registered via :meth:`add_on_return_callback`.

    :param callback: The callback to remove
    :returns:``True`` if the callback was removed, ``False`` if it was absent
    """
    return self.callbacks.remove_matching(self.channel_number, '_on_return',
                                          lambda cb: cb == callback)

tx_commit

tx_commit(
    callback: _OnTxCommitCallback | None = None,
) -> None

Commit a transaction.

PARAMETER DESCRIPTION
callback

callback(pika.frame.Method) for method Tx.CommitOk

TYPE: _OnTxCommitCallback | None DEFAULT: None

RETURNS DESCRIPTION
None

None. Method frame from the Tx.Commit-ok response is delivered to callback when provided.

RAISES DESCRIPTION
ValueError
Source code in pika/channel.py
def tx_commit(self, callback: _OnTxCommitCallback | None = None) -> None:
    """
    Commit a transaction.

    :param callback: callback(pika.frame.Method) for method Tx.CommitOk
    :returns:``None``. Method frame from the Tx.Commit-ok response is delivered to ``callback``
        when provided.
    :raises ValueError:
    """
    self._raise_if_not_open()
    validators.rpc_completion_callback(callback)
    return self._rpc(spec.Tx.Commit(), callback, [spec.Tx.CommitOk])

tx_rollback

tx_rollback(
    callback: _OnTxRollbackCallback | None = None,
) -> None

Rollback a transaction.

PARAMETER DESCRIPTION
callback

callback(pika.frame.Method) for method Tx.RollbackOk

TYPE: _OnTxRollbackCallback | None DEFAULT: None

RETURNS DESCRIPTION
None

None. Method frame from the Tx.Rollback-ok response is delivered to callback when provided.

RAISES DESCRIPTION
ValueError
Source code in pika/channel.py
def tx_rollback(self,
                callback: _OnTxRollbackCallback | None = None) -> None:
    """
    Rollback a transaction.

    :param callback: callback(pika.frame.Method) for method Tx.RollbackOk
    :returns:``None``. Method frame from the Tx.Rollback-ok response is delivered to
        ``callback`` when provided.
    :raises ValueError:
    """
    self._raise_if_not_open()
    validators.rpc_completion_callback(callback)
    return self._rpc(spec.Tx.Rollback(), callback, [spec.Tx.RollbackOk])

tx_select

tx_select(
    callback: _OnTxSelectCallback | None = None,
) -> None

Select standard transaction mode.

This method sets the channel to use standard transactions. The client must use this method at least once on a channel before using the Commit or Rollback methods.

PARAMETER DESCRIPTION
callback

callback(pika.frame.Method) for method Tx.SelectOk

TYPE: _OnTxSelectCallback | None DEFAULT: None

RETURNS DESCRIPTION
None

None. Method frame from the Tx.Select-ok response is delivered to callback when provided.

RAISES DESCRIPTION
ValueError
Source code in pika/channel.py
def tx_select(self, callback: _OnTxSelectCallback | None = None) -> None:
    """
    Select standard transaction mode.

    This method sets the channel to use standard transactions. The client must use this method
    at least once on a channel before using the Commit or Rollback methods.

    :param callback: callback(pika.frame.Method) for method Tx.SelectOk
    :returns:``None``. Method frame from the Tx.Select-ok response is delivered to ``callback``
        when provided.
    :raises ValueError:
    """
    self._raise_if_not_open()
    validators.rpc_completion_callback(callback)
    return self._rpc(spec.Tx.Select(), callback, [spec.Tx.SelectOk])

ContentFrameAssembler

Handle content related frames, building a message and return the message back in three parts upon receipt.

Source code in pika/channel.py
class ContentFrameAssembler:
    """Handle content related frames, building a message and return the message back in three parts
    upon receipt.
    """

    def __init__(self) -> None:
        """Create a new instance of the content frame assembler."""
        self._method_frame: frame.Method | None = None
        self._header_frame: frame.Header | None = None
        self._seen_so_far = 0
        self._body_fragments: list[bytes] = []

    def process(
        self, frame_value: frame.Frame
    ) -> tuple[frame.Method, frame.Header, bytes] | None:
        """
        Invoked by the Channel object when passed frames that are not setup in the rpc process and
        that don't have explicit reply types defined. This includes Basic.Publish, Basic.GetOk and
        Basic.Return.

        :param frame_value: The frame to process
        """
        frame_type = frame_value.frame_type
        if frame_type == spec.FRAME_METHOD:
            assert isinstance(frame_value, frame.Method)
            if spec.has_content(frame_value.method.INDEX):
                self._method_frame = frame_value
                return None
        elif frame_type == spec.FRAME_HEADER:
            assert isinstance(frame_value, frame.Header)
            self._header_frame = frame_value
            if frame_value.body_size == 0:
                return self._finish()
            return None
        elif frame_type == spec.FRAME_BODY:
            assert isinstance(frame_value, frame.Body)
            return self._handle_body_frame(frame_value)
        raise exceptions.UnexpectedFrameError(frame_value)

    def _finish(self) -> tuple[frame.Method, frame.Header, bytes]:
        """Invoked when all of the message has been received."""
        assert self._method_frame is not None
        assert self._header_frame is not None
        content = (self._method_frame, self._header_frame,
                   b''.join(self._body_fragments))
        self._reset()
        return content

    def _handle_body_frame(
        self, body_frame: frame.Body
    ) -> tuple[frame.Method, frame.Header, bytes] | None:
        """
        Receive body frames and append them to the stack.

        When the body size matches, call the finish method.

        :param body_frame: The body frame
        :raises: pika.exceptions.BodyTooLongError
        """
        self._seen_so_far += len(body_frame.fragment)
        self._body_fragments.append(body_frame.fragment)
        assert self._header_frame is not None
        if self._seen_so_far == self._header_frame.body_size:
            return self._finish()
        if self._seen_so_far > self._header_frame.body_size:
            raise exceptions.BodyTooLongError(self._seen_so_far,
                                              self._header_frame.body_size)
        return None

    def _reset(self) -> None:
        """Reset the values for processing frames."""
        self._method_frame = None
        self._header_frame = None
        self._seen_so_far = 0
        self._body_fragments = []

__init__

__init__() -> None

Create a new instance of the content frame assembler.

Source code in pika/channel.py
def __init__(self) -> None:
    """Create a new instance of the content frame assembler."""
    self._method_frame: frame.Method | None = None
    self._header_frame: frame.Header | None = None
    self._seen_so_far = 0
    self._body_fragments: list[bytes] = []

process

process(
    frame_value: Frame,
) -> tuple[Method, Header, bytes] | None

Invoked by the Channel object when passed frames that are not setup in the rpc process and that don't have explicit reply types defined. This includes Basic.Publish, Basic.GetOk and Basic.Return.

PARAMETER DESCRIPTION
frame_value

The frame to process

TYPE: Frame

Source code in pika/channel.py
def process(
    self, frame_value: frame.Frame
) -> tuple[frame.Method, frame.Header, bytes] | None:
    """
    Invoked by the Channel object when passed frames that are not setup in the rpc process and
    that don't have explicit reply types defined. This includes Basic.Publish, Basic.GetOk and
    Basic.Return.

    :param frame_value: The frame to process
    """
    frame_type = frame_value.frame_type
    if frame_type == spec.FRAME_METHOD:
        assert isinstance(frame_value, frame.Method)
        if spec.has_content(frame_value.method.INDEX):
            self._method_frame = frame_value
            return None
    elif frame_type == spec.FRAME_HEADER:
        assert isinstance(frame_value, frame.Header)
        self._header_frame = frame_value
        if frame_value.body_size == 0:
            return self._finish()
        return None
    elif frame_type == spec.FRAME_BODY:
        assert isinstance(frame_value, frame.Body)
        return self._handle_body_frame(frame_value)
    raise exceptions.UnexpectedFrameError(frame_value)

Channel

Channel

A Channel is the primary communication method for interacting with RabbitMQ.

It is recommended that you do not directly invoke the creation of a channel object in your application code but rather construct a channel by calling the active connection's channel() method.

Source code in pika/channel.py
class Channel:
    """
    A Channel is the primary communication method for interacting with RabbitMQ.

    It is recommended that you do not directly invoke the creation of a channel object in your
    application code but rather construct a channel by calling the active connection's channel()
    method.
    """

    CLOSED = 0
    OPENING = 1
    OPEN = 2
    CLOSING = 3  # client-initiated close in progress

    _STATE_NAMES: ClassVar[dict[int, str]] = {
        CLOSED: 'CLOSED',
        OPENING: 'OPENING',
        OPEN: 'OPEN',
        CLOSING: 'CLOSING'
    }

    _ON_CHANNEL_CLEANUP_CB_KEY = '_on_channel_cleanup'

    # Upper bound on the number of nowait-cancelled consumer tags retained in
    # `_cancelled`; see `_retain_cancelled_tag`.
    _MAX_RETAINED_CANCELLED_TAGS = 1024

    def __init__(self, connection: Connection, channel_number: int,
                 on_open_callback: _OnOpenCallback | None) -> None:
        """
        Create a new instance of the Channel.

        :param connection: The connection
        :param channel_number: The channel number for this instance
        :param on_open_callback: The callback to call on channel open. The callback will be invoked
            with the `Channel` instance as its only argument.
        """
        if not isinstance(channel_number, int):
            raise exceptions.InvalidChannelNumber(channel_number)

        validators.rpc_completion_callback(on_open_callback)

        self.channel_number = channel_number
        self.callbacks = connection.callbacks
        self.connection = connection

        # Initially, flow is assumed to be active
        self.flow_active = True

        self._content_assembler = ContentFrameAssembler()

        self._blocked: deque = deque()
        self._blocking: Any | None = None
        self._has_on_flow_callback: bool = False
        self._cancelled: set = set()
        # Nowait-cancelled tags in cancellation order, bounding how many of
        # them `_cancelled` retains; see `_retain_cancelled_tag`.
        self._nowait_cancelled: deque = deque()
        self._consumers: dict = {}
        self._consumers_with_noack: set = set()
        self._on_flowok_callback: Callable[..., Any] | None = None
        self._on_getok_callback: Callable[..., Any] | None = None
        self._on_ack_nack_callback: _OnAckNackCallback | None = None
        self._on_openok_callback: Callable[..., Any] | None = on_open_callback
        self._state: int = self.CLOSED

        # We save the closing reason exception to be passed to on-channel-close
        # callback at closing of the channel. Exception representing the closing
        # reason; ChannelClosedByClient or ChannelClosedByBroker on controlled
        # close; otherwise another exception describing the reason for failure
        # (most likely connection failure).
        self._closing_reason = None  # type: None | Exception

        # opaque cookie value set by wrapper layer (e.g., BlockingConnection)
        # via _set_cookie
        self._cookie: object = None

    def __int__(self) -> int:
        """Return the channel object as its channel number."""
        return self.channel_number

    @override
    def __repr__(self) -> str:
        return f'<{self.__class__.__name__} number={self.channel_number} {self._STATE_NAMES[self._state]} conn={self.connection!r}>'

    def add_callback(self,
                     callback: Callable[..., Any],
                     replies: Sequence[type[amqp_object.Method]],
                     one_shot: bool = True) -> None:
        """
        Pass in a callback handler and a list replies from the RabbitMQ broker which you'd like the
        callback notified of. Callbacks should allow for the frame parameter to be passed in.

        :param callback: The callback to call
        :param replies: The replies to get a callback for
        :param one_shot: Only handle the first type callback
        """
        for reply in replies:
            self.callbacks.add(self.channel_number, reply, callback, one_shot)

    def add_on_cancel_callback(self, callback: _OnCancelCallback) -> None:
        """
        Pass a callback function that will be called when the basic_cancel is sent by the server.
        The callback function should receive a frame parameter.

        :param callback: The callback to call on Basic.Cancel from broker
        """
        self.callbacks.add(self.channel_number, spec.Basic.Cancel, callback,
                           False)

    def add_on_close_callback(self, callback: _OnCloseCallback) -> None:
        """
        Pass a callback function that will be called when the channel is closed.

        The callback function will receive the channel and an exception describing why the channel
        was closed.

        If the channel is closed by broker via Channel.Close, the callback will receive
        `ChannelClosedByBroker` as the reason.

        If graceful user-initiated channel closing completes successfully ( either directly of
        indirectly by closing a connection containing the channel) and closing concludes gracefully
        without Channel.Close from the broker and without loss of connection, the callback will
        receive `ChannelClosedByClient` exception as reason.

        If channel was closed due to loss of connection, the callback will receive another exception
        type describing the failure.

        :param callback: The callback, having the signature: callback(Channel, Exception reason)
        """
        self.callbacks.add(self.channel_number, '_on_channel_close', callback,
                           False, self)

    def add_on_flow_callback(self, callback: _OnFlowCallback) -> None:
        """
        Pass a callback function that will be called when Channel.Flow is called by the remote
        server. Note that newer versions of RabbitMQ will not issue this but instead use TCP
        backpressure.

        :param callback: The callback function
        """
        self._has_on_flow_callback = True
        self.callbacks.add(self.channel_number, spec.Channel.Flow, callback,
                           False)

    def add_on_return_callback(self, callback: _OnReturnCallback) -> None:
        """
        Pass a callback function that will be called when basic_publish is sent a message that has
        been rejected and returned by the server.

        :param callback: The function to call, having the signature
                                callback(channel, method, properties, body)
                                where
                                - channel: pika.channel.Channel
                                - method: pika.spec.Basic.Return
                                - properties: pika.spec.BasicProperties
                                - body: bytes
        """
        self.callbacks.add(self.channel_number, '_on_return', callback, False)

    def remove_callback(
            self,
            callback: Callable[..., Any],
            replies: Sequence[type[amqp_object.Method]] | None = None) -> bool:
        """
        Remove a callback previously registered via :meth:`add_callback`.

        Mirrors :meth:`add_callback`: the callback is matched by identity and removed
        from each reply key it is registered under. If ``replies`` is ``None``, the
        callback is removed from every reply key it is currently registered under.

        :param callback: The callback to remove
        :param replies: The replies to remove the callback from, or ``None`` to
            remove it from every reply key it is registered under
        :returns: ``True`` if at least one matching callback was removed
        """
        reply_keys = (self.callbacks.keys(self.channel_number)
                      if replies is None else replies)
        removed = False
        for reply in reply_keys:
            if self.callbacks.remove_matching(self.channel_number, reply,
                                              lambda cb: cb == callback):
                removed = True
        return removed

    def remove_on_cancel_callback(self, callback: _OnCancelCallback) -> bool:
        """
        Remove a callback registered via :meth:`add_on_cancel_callback`.

        :param callback: The callback to remove
        :returns:``True`` if the callback was removed, ``False`` if it was absent
        """
        return self.callbacks.remove_matching(self.channel_number,
                                              spec.Basic.Cancel,
                                              lambda cb: cb == callback)

    def remove_on_close_callback(self, callback: _OnCloseCallback) -> bool:
        """
        Remove a callback registered via :meth:`add_on_close_callback`.

        :param callback: The callback to remove
        :returns:``True`` if the callback was removed, ``False`` if it was absent
        """
        return self.callbacks.remove_matching(self.channel_number,
                                              '_on_channel_close',
                                              lambda cb: cb == callback)

    def remove_on_flow_callback(self, callback: _OnFlowCallback) -> bool:
        """
        Remove a callback registered via :meth:`add_on_flow_callback`.

        :param callback: The callback to remove
        :returns:``True`` if the callback was removed, ``False`` if it was absent
        """
        return self.callbacks.remove_matching(self.channel_number,
                                              spec.Channel.Flow,
                                              lambda cb: cb == callback)

    def remove_on_return_callback(self, callback: _OnReturnCallback) -> bool:
        """
        Remove a callback registered via :meth:`add_on_return_callback`.

        :param callback: The callback to remove
        :returns:``True`` if the callback was removed, ``False`` if it was absent
        """
        return self.callbacks.remove_matching(self.channel_number, '_on_return',
                                              lambda cb: cb == callback)

    def basic_ack(self, delivery_tag: int = 0, multiple: bool = False) -> None:
        """
        Acknowledge one or more messages.

        When sent by the client, this method acknowledges one or more messages delivered via the
        Deliver or Get-Ok methods. When sent by server, this method acknowledges one or more
        messages published with the Publish method on a channel in confirm mode. The acknowledgement
        can be for a single message or a set of messages up to and including a specific message.

        :param delivery_tag: int/long The server-assigned delivery tag
        :param multiple: If set to True, the delivery tag is treated as "up to and including", so
            that multiple messages can be acknowledged with a single method. If set to False, the
            delivery tag refers to a single message. If the multiple field is 1, and the delivery
            tag is zero, this indicates acknowledgement of all outstanding messages.
        """
        self._raise_if_not_open()
        return self._send_method(spec.Basic.Ack(delivery_tag, multiple))

    def basic_cancel(self,
                     consumer_tag: str = '',
                     callback: _OnBasicCancelCallback | None = None) -> None:
        """
        This method cancels a consumer.

        This does not affect already delivered messages, but it does mean the server will not send
        any more messages for that consumer. The client may receive an arbitrary number of messages
        in between sending the cancel method and receiving the cancel-ok reply. It may also be sent
        from the server to the client in the event of the consumer being unexpectedly cancelled
        (i.e. cancelled for any reason other than the server receiving the corresponding
        basic.cancel from the client). This allows clients to be notified of the loss of consumers
        due to events such as queue deletion.

        A cancelled consumer's tag is retained so that a delivery already in flight when the cancel
        was sent is rejected rather than left unacknowledged. A cancel that expects a Basic.CancelOk
        retires its own entry on arrival; a nowait cancel has no reply to retire it, so its tag is
        kept only until `_MAX_RETAINED_CANCELLED_TAGS` later nowait cancels displace it (see
        `_retain_cancelled_tag`). Past that point its retention lapses: a straggling delivery for it
        is logged as unexpected and left unacknowledged rather than rejected, and the tag may be
        reused by `basic_consume`, so reusing the same explicit consumer_tag risks a delivery for
        the old consumer reaching the new one. The cap is a generous approximation of the broker's
        in-flight window, so this only bites under extreme nowait-cancel churn.

        :param consumer_tag: Identifier for the consumer
        :param callback: callback(pika.frame.Method) for method Basic.CancelOk. If None, do not
            expect a Basic.CancelOk response, otherwise, callback must be callable
        :raises ValueError:
        """
        validators.require_string(consumer_tag, 'consumer_tag')
        self._raise_if_not_open()
        nowait = validators.rpc_completion_callback(callback)

        if consumer_tag in self._cancelled:
            # We check for cancelled first, because basic_cancel removes
            # consumers closed with nowait from self._consumers
            LOGGER.warning('basic_cancel - consumer is already cancelling: %s',
                           consumer_tag)
            return

        if consumer_tag not in self._consumers:
            # Could be cancelled by user or broker earlier
            LOGGER.warning('basic_cancel - consumer not found: %s',
                           consumer_tag)
            return

        LOGGER.debug('Cancelling consumer: %s (nowait=%s)', consumer_tag,
                     nowait)

        if nowait:
            # This is our last opportunity while the channel is open to remove
            # this consumer callback and help gc.
            del self._consumers[consumer_tag]

        if callback is not None:
            self.callbacks.add(self.channel_number, spec.Basic.CancelOk,
                               callback)

        self._cancelled.add(consumer_tag)

        if nowait:
            self._retain_cancelled_tag(consumer_tag)

        self._rpc(spec.Basic.Cancel(consumer_tag=consumer_tag, nowait=nowait),
                  self._on_cancelok if not nowait else None,
                  [(spec.Basic.CancelOk, {
                      'consumer_tag': consumer_tag
                  })] if not nowait else [])

    def basic_consume(self,
                      queue: str,
                      on_message_callback: _OnMessageCallback,
                      auto_ack: bool = False,
                      exclusive: bool = False,
                      consumer_tag: str | None = None,
                      arguments: dict[str, Any] | None = None,
                      callback: _OnBasicConsumeCallback | None = None) -> str:
        """
        Sends the AMQP 0-9-1 command Basic.Consume to the broker and binds messages for the
        consumer_tag to the consumer callback. If you do not pass in a consumer_tag, one will be
        automatically generated for you. Returns the consumer tag.

        For more information on basic_consume, see:
        Tutorial 2 at https://www.rabbitmq.com/getstarted.html
        https://www.rabbitmq.com/confirms.html
        https://www.rabbitmq.com/amqp-0-9-1-reference.html#basic.consume

        :param queue: The queue to consume from. Use the empty string to
            specify the most recent server-named queue for this channel
        :param on_message_callback: The function to call when
            consuming with the signature
            on_message_callback(channel, method, properties, body), where
            - channel: pika.channel.Channel
            - method: pika.spec.Basic.Deliver
            - properties: pika.spec.BasicProperties
            - body: bytes
        :param auto_ack: if set to True, automatic acknowledgement mode
            will be used (see https://www.rabbitmq.com/confirms.html).
            This corresponds with the 'no_ack' parameter in the basic.consume
            AMQP 0.9.1 method
        :param exclusive: Don't allow other consumers on the queue
        :param consumer_tag: Specify your own consumer tag
        :param arguments: Custom key/value pair arguments for the consumer
        :param callback: callback(pika.frame.Method) for method
          Basic.ConsumeOk.
        :returns: Consumer tag which may be used to cancel the consumer.
        :raises ValueError:
        """
        validators.require_string(queue, 'queue')
        validators.require_callback(on_message_callback)
        self._raise_if_not_open()
        validators.rpc_completion_callback(callback)

        # If a consumer tag was not passed, create one
        if not consumer_tag:
            consumer_tag = self._generate_consumer_tag()

        if consumer_tag in self._consumers or consumer_tag in self._cancelled:
            raise exceptions.DuplicateConsumerTag(consumer_tag)

        if auto_ack:
            self._consumers_with_noack.add(consumer_tag)

        self._consumers[consumer_tag] = on_message_callback

        rpc_callback: Callable[
            ...,
            Any] | None = self._on_eventok if callback is None else callback

        self._rpc(
            spec.Basic.Consume(queue=queue,
                               consumer_tag=consumer_tag,
                               no_ack=auto_ack,
                               exclusive=exclusive,
                               arguments=arguments or {}), rpc_callback,
            [(spec.Basic.ConsumeOk, {
                'consumer_tag': consumer_tag
            })])

        return consumer_tag

    def _generate_consumer_tag(self) -> str:
        """
        Generate a consumer tag.

        NOTE: this protected method may be called by derived classes

        :returns: consumer tag
        """
        return f'ctag{self.channel_number}.{uuid.uuid4().hex}'

    def basic_get(self,
                  queue: str,
                  callback: _OnBasicGetCallback,
                  auto_ack: bool = False) -> None:
        """
        Get a single message from the AMQP broker.

        If you want to be notified of Basic.GetEmpty, use the Channel.add_callback method
        adding your Basic.GetEmpty callback which should expect only one
        parameter, frame. Due to implementation details, this cannot be called
        a second time until the callback is executed.  For more information on
        basic_get and its parameters, see:

        https://www.rabbitmq.com/amqp-0-9-1-reference.html#basic.get

        :param queue: The queue from which to get a message. Use the empty
            string to specify the most recent server-named queue for this
            channel
        :param callback: The callback to call with a message that has
            the signature callback(channel, method, properties, body), where:
            - channel: pika.channel.Channel
            - method: pika.spec.Basic.GetOk
            - properties: pika.spec.BasicProperties
            - body: bytes
        :param auto_ack: Tell the broker to not expect a reply
        :raises ValueError:
        """
        validators.require_string(queue, 'queue')
        validators.require_callback(callback)
        if self._on_getok_callback is not None:
            raise exceptions.DuplicateGetOkCallback()
        self._on_getok_callback = callback

        # TODO Strangely, not using _rpc for the synchronous Basic.Get. Would
        # need to extend _rpc to handle Basic.GetOk method, header, and body
        # frames (or similar)
        self._send_method(spec.Basic.Get(queue=queue, no_ack=auto_ack))

    def basic_nack(self,
                   delivery_tag: int = 0,
                   multiple: bool = False,
                   requeue: bool = True) -> None:
        """
        This method allows a client to reject one or more incoming messages.

        It can be used to interrupt and cancel large incoming messages, or return untreatable
        messages to their original queue.

        :param delivery_tag: int/long The server-assigned delivery tag
        :param multiple: If set to True, the delivery tag is treated as "up to and including", so
            that multiple messages can be acknowledged with a single method. If set to False, the
            delivery tag refers to a single message. If the multiple field is 1, and the delivery
            tag is zero, this indicates acknowledgement of all outstanding messages.
        :param requeue: If requeue is true, the server will attempt to requeue the message. If
            requeue is false or the requeue attempt fails the messages are discarded or dead-
            lettered.
        """
        self._raise_if_not_open()
        return self._send_method(
            spec.Basic.Nack(delivery_tag, multiple, requeue))

    def basic_publish(self,
                      exchange: str,
                      routing_key: str,
                      body: bytes,
                      properties: spec.BasicProperties | None = None,
                      mandatory: bool = False) -> None:
        """
        Publish to the channel with the given exchange, routing key and body.

        For more information on basic_publish and what the parameters do, see:

        https://www.rabbitmq.com/amqp-0-9-1-reference.html#basic.publish

        :param exchange: The exchange to publish to
        :param routing_key: The routing key to bind on
        :param body: The message body
        :param properties: Basic.properties
        :param mandatory: The mandatory flag
        """
        self._raise_if_not_open()
        body = as_bytes(body)
        properties = properties or spec.BasicProperties()
        self._send_method(
            spec.Basic.Publish(exchange=exchange,
                               routing_key=routing_key,
                               mandatory=mandatory), (properties, body))

    def basic_qos(self,
                  prefetch_size: int = 0,
                  prefetch_count: int = 0,
                  global_qos: bool = False,
                  callback: _OnBasicQosCallback | None = None) -> None:
        """
        Specify quality of service.

        This method requests a specific quality of service. The client can request that messages 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. The QoS can be
        applied separately to each new consumer on channel or shared across all consumers on the
        channel. Prefetching gives a performance improvement.

        :param prefetch_size: This field specifies the prefetch window size. 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 into other prefetch limits). May be set to zero, meaning "no specific
            limit", although other prefetch limits may still apply. The prefetch-size is ignored by
            consumers who have enabled the no-ack option.
        :param prefetch_count: Specifies a prefetch window in terms of whole messages. This field
            may be used in combination with the prefetch-size field; a message will only be sent in
            advance if both prefetch windows (and those at the channel and connection level) allow
            it. The prefetch-count is ignored by consumers who have enabled the no-ack option.
        :param global_qos: Should the QoS be shared across all consumers on the channel.
        :param callback: The callback to call for Basic.QosOk response
        :returns:``None``. Method frame from the Basic.Qos-ok response is delivered to ``callback``
            when provided.
        :raises ValueError:
        """
        self._raise_if_not_open()
        validators.rpc_completion_callback(callback)
        validators.zero_or_greater('prefetch_size', prefetch_size)
        validators.zero_or_greater('prefetch_count', prefetch_count)
        return self._rpc(
            spec.Basic.Qos(prefetch_size, prefetch_count, global_qos), callback,
            [spec.Basic.QosOk])

    def basic_reject(self, delivery_tag: int = 0, requeue: bool = True) -> None:
        """
        Reject an incoming message.

        This method allows a client to reject a message. It can be used to interrupt and cancel
        large incoming messages, or return untreatable messages to their original queue.

        :param delivery_tag: int/long The server-assigned delivery tag
        :param requeue: If requeue is true, the server will attempt to requeue the message. If
            requeue is false or the requeue attempt fails the messages are discarded or dead-
            lettered.
        :raises TypeError:
        """
        self._raise_if_not_open()
        if not isinstance(delivery_tag, int):
            raise TypeError('delivery_tag must be an integer')
        return self._send_method(spec.Basic.Reject(delivery_tag, requeue))

    def basic_recover(self,
                      requeue: bool = False,
                      callback: _OnBasicRecoverCallback | None = None) -> None:
        """
        This method asks the server to redeliver all unacknowledged messages on a specified channel.
        Zero or more messages may be redelivered. This method replaces the asynchronous Recover.

        :param requeue: If False, the message will be redelivered to the original recipient. If
            True, the server will attempt to requeue the message, potentially then delivering it to
            an alternative subscriber.
        :param callback: callback(pika.frame.Method) for method Basic.RecoverOk
        :returns:``None``. Method frame from the Basic.Recover-ok response is delivered to
            ``callback`` when provided.
        :raises ValueError:
        """
        self._raise_if_not_open()
        validators.rpc_completion_callback(callback)
        return self._rpc(spec.Basic.Recover(requeue), callback,
                         [spec.Basic.RecoverOk])

    def close(self,
              reply_code: int = 0,
              reply_text: str = 'Normal shutdown') -> None:
        """
        Invoke a graceful shutdown of the channel with the AMQP Broker.

        If channel is OPENING, transition to CLOSING and suppress the incoming Channel.OpenOk, if
        any.

        :param reply_code: The reason code to send to broker
        :param reply_text: The reason text to send to broker
        :raises ChannelWrongStateError: if channel is closed or closing
        """
        if self.is_closed or self.is_closing:
            # Whoever is calling `close` might expect the on-channel-close-cb
            # to be called, which won't happen when it's already closed.
            self._raise_if_not_open()

        # If channel is OPENING, we will transition it to CLOSING state,
        # causing the _on_openok method to suppress the OPEN state transition
        # and the on-channel-open-callback

        LOGGER.info('Closing channel (%s): %r on %s', reply_code, reply_text,
                    self)

        # Save the reason info so that we may use it in the '_on_channel_close'
        # callback processing
        self._closing_reason = exceptions.ChannelClosedByClient(
            reply_code, reply_text)

        for consumer_tag in list(self._consumers.keys()):
            if consumer_tag not in self._cancelled:
                self.basic_cancel(consumer_tag=consumer_tag)

        # Change state after cancelling consumers to avoid
        # ChannelWrongStateError exception from basic_cancel
        self._set_state(self.CLOSING)

        self._rpc(spec.Channel.Close(reply_code, reply_text, 0, 0),
                  self._on_closeok, [spec.Channel.CloseOk])

    def confirm_delivery(
            self,
            ack_nack_callback: _OnAckNackCallback,
            callback: _OnConfirmDeliveryCallback | None = None) -> None:
        """
        Turn on Confirm mode in the channel.

        Pass in a callback to be notified by the Broker when a message has been confirmed as received or
        rejected (Basic.Ack, Basic.Nack) from the broker to the publisher.

        For more information see:
            https://www.rabbitmq.com/confirms.html

        :param ack_nack_callback: Required callback for delivery
            confirmations that has the following signature:
            callback(pika.frame.Method), where method_frame contains
            either method `spec.Basic.Ack` or `spec.Basic.Nack`.
        :param callback: callback(pika.frame.Method) for method
            Confirm.SelectOk
        :raises TypeError: if `ack_nack_callback` is not callable

        .. note::
            Calling this method more than once on the same channel replaces
            the previously registered ``ack_nack_callback`` rather than adding
            an additional one. Only the most recently registered callback
            receives ``Basic.Ack``/``Basic.Nack`` notifications.
        """
        if not callable(ack_nack_callback):
            # confirm_deliver requires a callback; it's meaningless
            # without a user callback to receive Basic.Ack/Basic.Nack notifications
            raise TypeError('confirm_delivery requires a callback '
                            'to receive Basic.Ack/Basic.Nack notifications')

        self._raise_if_not_open()
        nowait = validators.rpc_completion_callback(callback)

        if not (self.connection.publisher_confirms and
                self.connection.basic_nack):
            raise exceptions.MethodNotImplemented(
                'Confirm.Select not Supported by Server')

        # Replace any previously registered ack/nack callback so repeated
        # calls don't stack listeners and fire stale callbacks (see #1602).
        if self._on_ack_nack_callback is not None:
            self.callbacks.remove(self.channel_number, spec.Basic.Ack,
                                  self._on_ack_nack_callback)
            self.callbacks.remove(self.channel_number, spec.Basic.Nack,
                                  self._on_ack_nack_callback)

        # Add the ack and nack callback
        self.callbacks.add(self.channel_number, spec.Basic.Ack,
                           ack_nack_callback, False)
        self.callbacks.add(self.channel_number, spec.Basic.Nack,
                           ack_nack_callback, False)
        self._on_ack_nack_callback = ack_nack_callback

        self._rpc(spec.Confirm.Select(nowait), callback,
                  [spec.Confirm.SelectOk] if not nowait else [])

    @property
    def consumer_tags(self) -> list[str]:
        """Property method that returns a list of currently active consumers."""
        return list(self._consumers.keys())

    def exchange_bind(self,
                      destination: str,
                      source: str,
                      routing_key: str = '',
                      arguments: dict[str, Any] | None = None,
                      callback: _OnExchangeBindCallback | None = None) -> None:
        """
        Bind an exchange to another exchange.

        :param destination: The destination exchange to bind
        :param source: The source exchange to bind to
        :param routing_key: The routing key to bind on
        :param arguments: Custom key/value pair arguments for the binding
        :param callback: callback(pika.frame.Method) for method Exchange.BindOk
        :returns:``None``. Method frame from the Exchange.Bind-ok response is delivered to
            ``callback`` when synchronous (no ok frame in nowait mode).
        :raises ValueError:
        """
        self._raise_if_not_open()
        validators.require_string(destination, 'destination')
        validators.require_string(source, 'source')
        nowait = validators.rpc_completion_callback(callback)
        return self._rpc(
            spec.Exchange.Bind(0, destination, source, routing_key, nowait,
                               arguments or {}), callback,
            [spec.Exchange.BindOk] if not nowait else [])

    def exchange_declare(
            self,
            exchange: str,
            exchange_type: str = ExchangeType.direct,
            passive: bool = False,
            durable: bool = False,
            auto_delete: bool = False,
            internal: bool = False,
            arguments: dict[str, Any] | None = None,
            callback: _OnExchangeDeclareCallback | None = None) -> None:
        """
        This method creates an exchange if it does not already exist, and if the exchange exists,
        verifies that it is of the correct and expected class.

        If passive set, the server will reply with Declare-Ok if the exchange
        already exists with the same name, and raise an error if not and if the
        exchange does not already exist, the server MUST raise a channel
        exception with reply code 404 (not found).

        :param exchange: The exchange name consists of a non-empty sequence
            of these characters: letters, digits, hyphen, underscore, period,
            or colon
        :param exchange_type: The exchange type to use
        :param passive: Perform a declare or just check to see if it exists
        :param durable: Survive a reboot of RabbitMQ
        :param auto_delete: Remove when no more queues are bound to it
        :param internal: Can only be published to by other exchanges
        :param arguments: Custom key/value pair arguments for the exchange
        :param callback: callback(pika.frame.Method) for method Exchange.DeclareOk
        :returns: ``None``. Method frame from the Exchange.Declare-ok response is
            delivered to ``callback`` when synchronous (no ok frame in nowait
            mode).
        :raises ValueError:
        """
        validators.require_string(exchange, 'exchange')
        self._raise_if_not_open()
        nowait = validators.rpc_completion_callback(callback)
        if isinstance(exchange_type, Enum):
            exchange_type = exchange_type.value
        return self._rpc(
            spec.Exchange.Declare(0, exchange, exchange_type, passive, durable,
                                  auto_delete, internal, nowait, arguments or
                                  {}), callback,
            [spec.Exchange.DeclareOk] if not nowait else [])

    def exchange_delete(
            self,
            exchange: str | None = None,
            if_unused: bool = False,
            callback: _OnExchangeDeleteCallback | None = None) -> None:
        """
        Delete the exchange.

        :param exchange: The exchange name
        :param if_unused: only delete if the exchange is unused
        :param callback: callback(pika.frame.Method) for method Exchange.DeleteOk
        :returns:``None``. Method frame from the Exchange.Delete-ok response is delivered to
            ``callback`` when synchronous (no ok frame in nowait mode).
        :raises ValueError:
        """
        self._raise_if_not_open()
        nowait = validators.rpc_completion_callback(callback)
        return self._rpc(spec.Exchange.Delete(0, exchange, if_unused,
                                              nowait), callback,
                         [spec.Exchange.DeleteOk] if not nowait else [])

    def exchange_unbind(
            self,
            destination: str | None = None,
            source: str | None = None,
            routing_key: str = '',
            arguments: dict[str, Any] | None = None,
            callback: _OnExchangeUnbindCallback | None = None) -> None:
        """
        Unbind an exchange from another exchange.

        :param destination: The destination exchange to unbind
        :param source: The source exchange to unbind from
        :param routing_key: The routing key to unbind
        :param arguments: Custom key/value pair arguments for the binding
        :param callback: callback(pika.frame.Method) for method Exchange.UnbindOk
        :returns:``None``. Method frame from the Exchange.Unbind-ok response is delivered to
            ``callback`` when synchronous (no ok frame in nowait mode).
        :raises ValueError:
        """
        self._raise_if_not_open()
        nowait = validators.rpc_completion_callback(callback)
        return self._rpc(
            spec.Exchange.Unbind(0, destination, source, routing_key, nowait,
                                 arguments), callback,
            [spec.Exchange.UnbindOk] if not nowait else [])

    def flow(self,
             active: bool,
             callback: _OnFlowCallback | None = None) -> None:
        """
        Turn Channel flow control off and on.

        Pass a callback to be notified of the response from the server. active is a bool. Callback
        should expect a bool in response indicating channel flow state. For more information, please
        reference:

        https://www.rabbitmq.com/amqp-0-9-1-reference.html#channel.flow

        :param active: Turn flow on or off
        :param callback: callback(bool) upon completion
        :raises ValueError:
        """
        self._raise_if_not_open()
        validators.rpc_completion_callback(callback)
        self._on_flowok_callback = callback
        self._rpc(spec.Channel.Flow(active), self._on_flowok,
                  [spec.Channel.FlowOk])

    @property
    def is_closed(self) -> bool:
        """Returns True if the channel is closed."""
        return self._state == self.CLOSED

    @property
    def is_closing(self) -> bool:
        """Returns True if client-initiated closing of the channel is in progress."""
        return self._state == self.CLOSING

    @property
    def is_open(self) -> bool:
        """Returns True if the channel is open."""
        return self._state == self.OPEN

    @property
    def is_opening(self) -> bool:
        """Returns True if the channel is opening."""
        return self._state == self.OPENING

    def open(self) -> None:
        """Open the channel."""
        self._set_state(self.OPENING)
        self._add_callbacks()
        self._rpc(spec.Channel.Open(), self._on_openok, [spec.Channel.OpenOk])

    def queue_bind(self,
                   queue: str,
                   exchange: str,
                   routing_key: str | None = None,
                   arguments: dict[str, Any] | None = None,
                   callback: _OnQueueBindCallback | None = None) -> None:
        """
        Bind the queue to the specified exchange.

        :param queue: The queue to bind to the exchange
        :param exchange: The source exchange to bind to
        :param routing_key: The routing key to bind on
        :param arguments: Custom key/value pair arguments for the binding
        :param callback: callback(pika.frame.Method) for method Queue.BindOk
        :returns:``None``. Method frame from the Queue.Bind-ok response is delivered to ``callback``
            when synchronous (no ok frame in nowait mode).
        :raises ValueError:
        """
        validators.require_string(queue, 'queue')
        validators.require_string(exchange, 'exchange')
        self._raise_if_not_open()
        nowait = validators.rpc_completion_callback(callback)
        if routing_key is None:
            routing_key = queue
        return self._rpc(
            spec.Queue.Bind(0, queue, exchange, routing_key, nowait,
                            arguments or {}), callback,
            [spec.Queue.BindOk] if not nowait else [])

    def queue_declare(self,
                      queue: str,
                      passive: bool = False,
                      durable: bool = False,
                      exclusive: bool = False,
                      auto_delete: bool = False,
                      arguments: dict[str, Any] | None = None,
                      callback: _OnQueueDeclareCallback | None = None) -> None:
        """
        Declare queue, create if needed.

        This method creates or checks a queue. When creating a new queue the client can specify various
        properties that control the durability of the queue and its contents,
        and the level of sharing for the queue.

        Use an empty string as the queue name for the broker to auto-generate
        one

        :param queue: The queue name; if empty string, the broker will
            create a unique queue name
        :param passive: Only check to see if the queue exists
        :param durable: Survive reboots of the broker
        :param exclusive: Only allow access by the current connection
        :param auto_delete: Delete after consumer cancels or disconnects
        :param arguments: Custom key/value arguments for the queue
        :param callback: callback(pika.frame.Method) for method Queue.DeclareOk
        :returns: ``None``. Method frame from the Queue.Declare-ok response is
            delivered to ``callback`` when synchronous (no ok frame in nowait
            mode).
        :raises ValueError:
        """
        validators.require_string(queue, 'queue')
        self._raise_if_not_open()
        nowait = validators.rpc_completion_callback(callback)

        condition: Any
        if queue:
            condition = (spec.Queue.DeclareOk, {'queue': queue})
        else:
            condition = spec.Queue.DeclareOk
        replies = [condition] if not nowait else []

        return self._rpc(
            spec.Queue.Declare(0, queue, passive, durable, exclusive,
                               auto_delete, nowait, arguments or {}), callback,
            replies)

    def queue_delete(self,
                     queue: str,
                     if_unused: bool = False,
                     if_empty: bool = False,
                     callback: _OnQueueDeleteCallback | None = None) -> None:
        """
        Delete a queue from the broker.

        :param queue: The queue to delete
        :param if_unused: only delete if it's unused
        :param if_empty: only delete if the queue is empty
        :param callback: callback(pika.frame.Method) for method Queue.DeleteOk
        :returns:``None``. Method frame from the Queue.Delete-ok response is delivered to
            ``callback`` when synchronous (no ok frame in nowait mode).
        :raises ValueError:
        """
        self._raise_if_not_open()
        validators.require_string(queue, 'queue')
        nowait = validators.rpc_completion_callback(callback)
        replies = [spec.Queue.DeleteOk] if not nowait else []
        return self._rpc(
            spec.Queue.Delete(0, queue, if_unused, if_empty, nowait), callback,
            replies)

    def queue_purge(self,
                    queue: str,
                    callback: _OnQueuePurgeCallback | None = None) -> None:
        """
        Purge all of the messages from the specified queue.

        :param queue: The queue to purge
        :param callback: callback(pika.frame.Method) for method Queue.PurgeOk
        :returns:``None``. Method frame from the Queue.Purge-ok response is delivered to
            ``callback`` when synchronous (no ok frame in nowait mode).
        :raises ValueError:
        """
        self._raise_if_not_open()
        validators.require_string(queue, 'queue')
        nowait = validators.rpc_completion_callback(callback)
        replies = [spec.Queue.PurgeOk] if not nowait else []
        return self._rpc(spec.Queue.Purge(0, queue, nowait), callback, replies)

    def queue_unbind(self,
                     queue: str,
                     exchange: str | None = None,
                     routing_key: str | None = None,
                     arguments: dict[str, Any] | None = None,
                     callback: _OnQueueUnbindCallback | None = None) -> None:
        """
        Unbind a queue from an exchange.

        :param queue: The queue to unbind from the exchange
        :param exchange: The source exchange to bind from
        :param routing_key: The routing key to unbind
        :param arguments: Custom key/value pair arguments for the binding
        :param callback: callback(pika.frame.Method) for method Queue.UnbindOk
        :returns:``None``. Method frame from the Queue.Unbind-ok response is delivered to
            ``callback`` when provided.
        :raises ValueError:
        """
        self._raise_if_not_open()
        validators.require_string(queue, 'queue')
        validators.rpc_completion_callback(callback)
        if routing_key is None:
            routing_key = queue
        return self._rpc(
            spec.Queue.Unbind(0, queue, exchange, routing_key, arguments or {}),
            callback, [spec.Queue.UnbindOk])

    def tx_commit(self, callback: _OnTxCommitCallback | None = None) -> None:
        """
        Commit a transaction.

        :param callback: callback(pika.frame.Method) for method Tx.CommitOk
        :returns:``None``. Method frame from the Tx.Commit-ok response is delivered to ``callback``
            when provided.
        :raises ValueError:
        """
        self._raise_if_not_open()
        validators.rpc_completion_callback(callback)
        return self._rpc(spec.Tx.Commit(), callback, [spec.Tx.CommitOk])

    def tx_rollback(self,
                    callback: _OnTxRollbackCallback | None = None) -> None:
        """
        Rollback a transaction.

        :param callback: callback(pika.frame.Method) for method Tx.RollbackOk
        :returns:``None``. Method frame from the Tx.Rollback-ok response is delivered to
            ``callback`` when provided.
        :raises ValueError:
        """
        self._raise_if_not_open()
        validators.rpc_completion_callback(callback)
        return self._rpc(spec.Tx.Rollback(), callback, [spec.Tx.RollbackOk])

    def tx_select(self, callback: _OnTxSelectCallback | None = None) -> None:
        """
        Select standard transaction mode.

        This method sets the channel to use standard transactions. The client must use this method
        at least once on a channel before using the Commit or Rollback methods.

        :param callback: callback(pika.frame.Method) for method Tx.SelectOk
        :returns:``None``. Method frame from the Tx.Select-ok response is delivered to ``callback``
            when provided.
        :raises ValueError:
        """
        self._raise_if_not_open()
        validators.rpc_completion_callback(callback)
        return self._rpc(spec.Tx.Select(), callback, [spec.Tx.SelectOk])

    # Internal methods

    def _add_callbacks(self) -> None:
        """Callbacks that add the required behavior for a channel when connecting and connected to a
        server.
        """
        # Add a callback for Basic.GetEmpty
        self.callbacks.add(self.channel_number, spec.Basic.GetEmpty,
                           self._on_getempty, False)

        # Add a callback for Basic.Cancel
        self.callbacks.add(self.channel_number, spec.Basic.Cancel,
                           self._on_cancel, False)

        # Deprecated in newer versions of RabbitMQ but still register for it
        self.callbacks.add(self.channel_number, spec.Channel.Flow,
                           self._on_flow, False)

        # Add a callback for when the server closes our channel
        self.callbacks.add(self.channel_number, spec.Channel.Close,
                           self._on_close_from_broker, True)

    def _add_on_cleanup_callback(self, callback: Callable[..., Any]) -> None:
        """
        For internal use only (e.g., Connection needs to remove closed channels from its channel
        container). Pass a callback function that will be called when the channel is being cleaned
        up after all channel-close callbacks callbacks.

        :param callback: The callback to call, having the
            signature: callback(channel)
        """
        self.callbacks.add(self.channel_number,
                           self._ON_CHANNEL_CLEANUP_CB_KEY,
                           callback,
                           one_shot=True,
                           only_caller=self)

    def _cleanup(self) -> None:
        """Remove all consumers and any callbacks for the channel."""
        self.callbacks.process(self.channel_number,
                               self._ON_CHANNEL_CLEANUP_CB_KEY, self, self)
        self._consumers = {}
        self._cancelled = set()
        self._nowait_cancelled = deque()
        self._consumers_with_noack = set()
        self.callbacks.cleanup(str(self.channel_number))
        self._cookie = None

    def _cleanup_consumer_ref(self, consumer_tag: str) -> None:
        """
        Remove any references to the consumer tag in internal structures for consumer state.

        :param consumer_tag: The consumer tag to cleanup
        """
        self._consumers_with_noack.discard(consumer_tag)
        self._consumers.pop(consumer_tag, None)
        self._cancelled.discard(consumer_tag)

    def _retain_cancelled_tag(self, consumer_tag: str) -> None:
        """
        Retain a nowait-cancelled consumer tag, evicting the oldest once the cap is reached.

        A cancelled tag stays in `_cancelled` (and `_consumers_with_noack`) so that a delivery the
        broker had already dispatched when `Basic.Cancel` was sent is rejected rather than left
        unacknowledged; see `_on_deliver`.  A cancel that expects a `Basic.CancelOk` retires its own
        entry in `_on_cancelok`, but a nowait cancel asks the broker for no reply, so nothing
        retires it and the entries would otherwise accumulate for the life of the channel.

        Bound them here instead.  The number of deliveries that can still be in flight for a
        cancelled consumer is bounded by what the broker had already dispatched, so a cap on
        retained nowait-cancelled tags approximates that window: evicting in cancellation order past
        `_MAX_RETAINED_CANCELLED_TAGS` keeps retention constant in the number of cancels.  The cap
        is not the true window, though, since it is measured in cancels rather than deliveries, so
        once a tag is evicted its reject-and-reserve behaviour lapses: a straggling delivery for it
        is logged as unexpected and left unacknowledged (see `_on_deliver`), and `basic_consume`
        will accept the tag again.  The default is large enough that this only occurs under extreme
        nowait-cancel churn.

        A tag cannot be queued twice: `basic_consume` refuses a tag that is still in `_cancelled`,
        and on the nowait path only eviction takes it back out again.

        :param consumer_tag: The consumer tag just cancelled with nowait
        """
        self._nowait_cancelled.append(consumer_tag)
        while len(self._nowait_cancelled) > self._MAX_RETAINED_CANCELLED_TAGS:
            self._cleanup_consumer_ref(self._nowait_cancelled.popleft())

    def _get_cookie(self) -> Any:
        """
        Used by the wrapper implementation (e.g., `BlockingChannel`) to retrieve the cookie that it
        set via `_set_cookie`

        :returns: opaque cookie value that was set via `_set_cookie`
        """
        return self._cookie

    def _handle_content_frame(self, frame_value: frame.Frame) -> None:
        """
        This is invoked by the connection when frames that are not registered with the
        CallbackManager have been found. This should only be the case when the frames are related to
        content delivery.

        The _content_assembler will be invoked which will return the fully formed message in three
        parts when all of the body frames have been received.

        :param frame_value: The frame to deliver
        """
        try:
            response = self._content_assembler.process(frame_value)
        except exceptions.UnexpectedFrameError:
            self._on_unexpected_frame(frame_value)
            return

        if response:
            method_index = response[0].method.INDEX
            if method_index == spec.Basic.Deliver.INDEX:
                self._on_deliver(*response)
            elif method_index == spec.Basic.GetOk.INDEX:
                self._on_getok(*response)
            elif method_index == spec.Basic.Return.INDEX:
                self._on_return(*response)

    def _on_cancel(self, method_frame: frame.Method) -> None:
        """
        When the broker cancels a consumer, delete it from our internal dictionary.

        Reply with `Basic.CancelOk` if the broker advertises the `accept_consumer_cancel_ok`
        capability.

        :param method_frame: The method frame received
        """
        consumer_tag = method_frame.method.consumer_tag
        # Sent before the `_cancelled` check below, so a user-initiated cancel
        # racing a broker-sent one still gets a reply. That is safe in both
        # orders, which is not obvious from here. A broker advertising the
        # capability answers a `Basic.CancelOk` for a tag it is not waiting on
        # with `{noreply, State}`, so a late or duplicate reply is ignored
        # rather than treated as a protocol error. And if this reply reaches the
        # broker first, it releases the consumer without replying, leaving the
        # user's in-flight `Basic.Cancel` to arrive for a tag the broker no
        # longer tracks - which `cancel_consumer` answers with a `Basic.CancelOk`
        # anyway ("Spec requires we ignore this situation"), so the pending RPC
        # still completes instead of hanging.
        if self.is_open and self.connection.accept_consumer_cancel_ok:
            self._send_method(spec.Basic.CancelOk(consumer_tag=consumer_tag))

        if consumer_tag in self._cancelled:
            # User-initiated cancel is waiting for Cancel-ok
            return

        self._cleanup_consumer_ref(consumer_tag)

    def _on_cancelok(self, method_frame: frame.Method) -> None:
        """
        Called in response to a frame from the Broker when the client sends Basic.Cancel.

        :param method_frame: The method frame received
        """
        self._cleanup_consumer_ref(method_frame.method.consumer_tag)

    def _transition_to_closed(self) -> None:
        """Common logic for transitioning the channel to the CLOSED state:

        Set state to CLOSED, dispatch callbacks registered via
        `Channel.add_on_close_callback()`, and mop up.

        Assumes that the channel is not in CLOSED state and that
        `self._closing_reason` has been set up

        """
        assert not self.is_closed
        assert self._closing_reason is not None

        self._set_state(self.CLOSED)

        try:
            self.callbacks.process(self.channel_number, '_on_channel_close',
                                   self, self, self._closing_reason)
        finally:
            self._cleanup()

    def _on_close_from_broker(self, method_frame: frame.Method) -> None:
        """
        Handle `Channel.Close` from broker.

        :param method_frame: Method frame with Channel.Close method
        """
        LOGGER.warning('Received remote Channel.Close (%s): %r on %s',
                       method_frame.method.reply_code,
                       method_frame.method.reply_text, self)
        # Note, we should not be called when channel is already closed
        assert not self.is_closed

        # AMQP 0.9.1 requires CloseOk response to Channel.Close;
        self._send_method(spec.Channel.CloseOk())

        # Save the details, possibly overriding user-provided values if
        # user-initiated close is pending (in which case they will be provided
        # to user callback when CloseOk arrives).
        self._closing_reason = exceptions.ChannelClosedByBroker(
            method_frame.method.reply_code, method_frame.method.reply_text)

        if self.is_closing:
            # Since we may have already put Channel.Close on the wire, we need
            # to wait for CloseOk before cleaning up to avoid a race condition
            # whereby our channel number might get reused before our CloseOk
            # arrives
            #
            # NOTE: if our Channel.Close destined for the broker was blocked by
            # an earlier synchronous method, this call will drop it and perform
            # a meta-close (see `_on_close_meta()` which fakes receipt of
            # `Channel.CloseOk` and dispatches the `'_on_channel_close'`
            # callbacks.
            self._drain_blocked_methods_on_remote_close()
        else:
            self._transition_to_closed()

    def _on_close_meta(self, reason: Exception | None) -> None:
        """
        Handle meta-close request from either a remote Channel.Close from the broker (when a pending
        Channel.Close method is queued for execution) or a Connection's cleanup logic after sudden
        connection loss. We use this opportunity to transition to CLOSED state, clean up the
        channel, and dispatch the on-channel-closed callbacks.

        :param reason: Exception describing the reason for closing.
        """
        LOGGER.debug('Handling meta-close on %s: %r', self, reason)

        if not self.is_closed:
            self._closing_reason = reason
            self._transition_to_closed()

    def _on_closeok(self, method_frame: frame.Method) -> None:
        """
        Invoked when RabbitMQ replies to a Channel.Close method.

        :param method_frame: Method frame with Channel.CloseOk method
        """
        LOGGER.info('Received %s on %s', method_frame.method, self)

        self._transition_to_closed()

    def _on_deliver(self, method_frame: frame.Method,
                    header_frame: frame.Header, body: bytes) -> None:
        """
        Cope with reentrancy.

        If a particular consumer is still active when another delivery appears for it, queue the
        deliveries up until it finally exits.

        :param method_frame: The method frame received
        :param header_frame: The header frame received
        :param body: The body received
        """
        consumer_tag = method_frame.method.consumer_tag

        if consumer_tag in self._cancelled:
            if self.is_open and consumer_tag not in self._consumers_with_noack:
                self.basic_reject(method_frame.method.delivery_tag)
            return

        if consumer_tag not in self._consumers:
            LOGGER.error('Unexpected delivery: %r', method_frame)
            return

        self._consumers[consumer_tag](self, method_frame.method,
                                      header_frame.properties, body)

    def _on_eventok(self, method_frame: frame.Method) -> None:
        """
        Generic events that returned ok that may have internal callbacks.

        We keep a list of what we've yet to implement so that we don't silently drain events that we
        don't support.

        :param method_frame: The method frame received
        """
        LOGGER.debug('Discarding frame %r', method_frame)

    def _on_flow(self, _method_frame_unused: frame.Method) -> None:
        """
        Called if the server sends a Channel.Flow frame.

        :param _method_frame_unused: The Channel.Flow frame
        """
        if self._has_on_flow_callback is False:
            LOGGER.warning('Channel.Flow received from server')

    def _on_flowok(self, method_frame: frame.Method) -> None:
        """
        Called in response to us asking the server to toggle on Channel.Flow.

        :param method_frame: The method frame received
        """
        self.flow_active = method_frame.method.active
        if self._on_flowok_callback:
            self._on_flowok_callback(method_frame.method.active)
            self._on_flowok_callback = None
        else:
            LOGGER.warning('Channel.FlowOk received with no active callbacks')

    def _on_getempty(self, method_frame: frame.Method) -> None:
        """
        When we receive an empty reply do nothing but log it.

        :param method_frame: The method frame received
        """
        LOGGER.debug('Received Basic.GetEmpty: %r', method_frame)
        if self._on_getok_callback is not None:
            self._on_getok_callback = None

    def _on_getok(self, method_frame: frame.Method, header_frame: frame.Header,
                  body: bytes) -> None:
        """
        Called in reply to a Basic.Get when there is a message.

        :param method_frame: The method frame received
        :param header_frame: The header frame received
        :param body: The body received
        """
        if self._on_getok_callback is not None:
            callback = self._on_getok_callback
            self._on_getok_callback = None
            callback(self, method_frame.method, header_frame.properties, body)
        else:
            LOGGER.error('Basic.GetOk received with no active callback')

    def _on_openok(self, method_frame: frame.Method) -> None:
        """
        Called by our callback handler when we receive a Channel.OpenOk and subsequently calls our
        _on_openok_callback which was passed into the Channel constructor. The reason we do this is
        because we want to make sure that the on_open_callback parameter passed into the Channel
        constructor is not the first callback we make.

        Suppress the state transition and callback if channel is already in CLOSING state.

        :param method_frame: Channel.OpenOk frame
        """
        # Suppress OpenOk if the user or Connection.Close started closing it
        # before open completed.
        if self.is_closing:
            LOGGER.debug('Suppressing while in closing state: %s', method_frame)
        else:
            self._set_state(self.OPEN)
            if self._on_openok_callback is not None:
                self._on_openok_callback(self)

    def _on_return(self, method_frame: frame.Method, header_frame: frame.Header,
                   body: bytes) -> None:
        """
        Called if the server sends a Basic.Return frame.

        :param method_frame: The Basic.Return frame
        :param header_frame: The content header frame
        :param body: The message body
        """
        if not self.callbacks.process(self.channel_number, '_on_return', self,
                                      self, method_frame.method,
                                      header_frame.properties, body):
            LOGGER.debug('Basic.Return received from server (%r, %r)',
                         method_frame.method, header_frame.properties)

    def _on_selectok(self, method_frame: frame.Method) -> None:
        """
        Called when the broker sends a Confirm.SelectOk frame.

        :param method_frame: The method frame received
        """
        LOGGER.debug('Confirm.SelectOk Received: %r', method_frame)

    def _on_synchronous_complete(self,
                                 _method_frame_unused: frame.Method) -> None:
        """
        This is called when a synchronous command is completed.

        It will undo the blocking state and send all the frames that stacked up while we were in the
        blocking state.

        :param _method_frame_unused: The method frame received
        """
        LOGGER.debug('%i blocked frames', len(self._blocked))
        self._blocking = None
        # self._blocking must be checked here as a callback could
        # potentially change the state of that variable during an
        # iteration of the while loop
        while self._blocked and self._blocking is None:
            self._rpc(*self._blocked.popleft())

    def _drain_blocked_methods_on_remote_close(self) -> None:
        """
        This is called when the broker sends a Channel.Close while the client is in CLOSING state.
        This method checks the blocked method queue for a pending client-initiated Channel.Close
        method and ensures its callbacks are processed, but does not send the method to the broker.

        The broker may close the channel before responding to outstanding in-transit synchronous
        methods, or even before these methods have been sent to the broker. AMQP 0.9.1 obliges the
        server to drop all methods arriving on a closed channel other than Channel.CloseOk and
        Channel.Close. Since the response to a synchronous method that blocked the channel never
        arrives, the channel never becomes unblocked, and the Channel.Close, if any, in the blocked
        queue has no opportunity to be sent, and thus its completion callback would never be called.
        """
        LOGGER.debug(
            'Draining %i blocked frames due to broker-requested Channel.Close',
            len(self._blocked))
        while self._blocked:
            method = self._blocked.popleft()[0]
            if isinstance(method, spec.Channel.Close):
                # The desired reason is already in self._closing_reason
                self._on_close_meta(self._closing_reason)
            else:
                LOGGER.debug('Ignoring drained blocked method: %s', method)

    def _rpc(
        self,
        method: amqp_object.Method,
        callback: Callable[..., Any] | None = None,
        acceptable_replies: Sequence[type[amqp_object.Method] |
                                     tuple[type[amqp_object.Method],
                                           dict[str, Any]]] | None = None
    ) -> None:
        """
        Make a synchronous channel RPC call for a synchronous method frame.

        If the channel is already in the blocking state, then enqueue the request,
        but don't send it at this time; it will be eventually sent by
        `_on_synchronous_complete` after the prior blocking request receives a
        response. If the channel is not in the blocking state and
        `acceptable_replies` is not empty, transition the channel to the
        blocking state and register for `_on_synchronous_complete` before
        sending the request.

        NOTE: A callback must be accompanied by non-empty acceptable_replies.

        :param method: The AMQP method to invoke
        :param callback: The callback for the RPC response
        :param acceptable_replies: A (possibly empty) sequence of
            replies this RPC call expects or None
        """
        assert method.synchronous, (
            f'Only synchronous-capable methods may be used with _rpc: {method!r}'
        )

        # Validate we got None or a list of acceptable_replies
        if not isinstance(acceptable_replies, (type(None), list)):
            raise TypeError('acceptable_replies should be list or None')

        if callback is not None:
            # Validate the callback is callable
            if not callable(callback):
                raise TypeError('callback should be None or a callable')

            # Make sure that callback is accompanied by acceptable replies
            if not acceptable_replies:
                raise ValueError(
                    'Unexpected callback for asynchronous (nowait) operation.')

        # Make sure the channel is not closed yet
        if self.is_closed:
            self._raise_if_not_open()

        # If the channel is blocking, add subsequent commands to our stack
        if self._blocking:
            LOGGER.debug(
                'Already in blocking state, so enqueueing method %s; '
                'acceptable_replies=%r', method, acceptable_replies)
            self._blocked.append([method, callback, acceptable_replies])
            return

        # Note: _send_method can throw exceptions if there are framing errors
        # or invalid data passed in. Call it here to prevent self._blocking
        # from being set if an exception is thrown. This also prevents
        # acceptable_replies registering callbacks when exceptions are thrown
        self._send_method(method)

        # If acceptable replies are set, add callbacks
        if acceptable_replies:
            # Block until a response frame is received for synchronous frames
            self._blocking = method.NAME
            LOGGER.debug(
                'Entering blocking state on frame %s; acceptable_replies=%r',
                method, acceptable_replies)

            for reply in acceptable_replies:
                if isinstance(reply, tuple):
                    reply, arguments = reply
                else:
                    arguments = None
                LOGGER.debug('Adding on_synchronous_complete callback')
                self.callbacks.add(self.channel_number,
                                   reply,
                                   self._on_synchronous_complete,
                                   arguments=arguments)
                if callback is not None:
                    LOGGER.debug('Adding passed-in RPC response callback')
                    self.callbacks.add(self.channel_number,
                                       reply,
                                       callback,
                                       arguments=arguments)

    def _raise_if_not_open(self) -> None:
        """
        If channel is not in the OPEN state, raises ChannelWrongStateError with `reply_code` and
        `reply_text` corresponding to current state.

        :raises exceptions.ChannelWrongStateError: if channel is not in OPEN state.
        """
        if self._state == self.OPEN:
            return

        if self._state == self.OPENING:
            raise exceptions.ChannelWrongStateError(
                'Channel is opening, but is not usable yet.')

        if self._state == self.CLOSING:
            raise exceptions.ChannelWrongStateError('Channel is closing.')

        # Assumed self.CLOSED
        assert self._state == self.CLOSED
        raise exceptions.ChannelWrongStateError('Channel is closed.')

    def _send_method(
            self,
            method: amqp_object.Method,
            content: tuple[spec.BasicProperties, bytes] | None = None) -> None:
        """
        Shortcut wrapper to send a method through our connection, passing in the channel number.

        :param method: The method to send
        :param content: If set, is a content frame, is tuple of properties and body.
        """
        self.connection._send_method(self.channel_number, method, content)

    def _set_cookie(self, cookie: object) -> None:
        """
        Used by wrapper layer (e.g., `BlockingConnection`) to link the channel implementation back
        to the proxy. See `_get_cookie`.

        :param cookie: an opaque value; typically a proxy channel implementation instance (e.g.,
            `BlockingChannel` instance)
        """
        self._cookie = cookie

    def _set_state(self, connection_state: int) -> None:
        """
        Set the channel connection state to the specified state value.

        :param connection_state: The connection_state value
        """
        self._state = connection_state

    def _on_unexpected_frame(self, frame_value: frame.Frame) -> None:
        """
        Invoked when a frame is received that is not setup to be processed.

        :param frame_value: The frame received
        """
        LOGGER.error('Unexpected frame: %r', frame_value)

CLOSED class-attribute instance-attribute

CLOSED = 0

OPENING class-attribute instance-attribute

OPENING = 1

OPEN class-attribute instance-attribute

OPEN = 2

CLOSING class-attribute instance-attribute

CLOSING = 3

_STATE_NAMES class-attribute

_STATE_NAMES: dict[int, str] = {
    CLOSED: 'CLOSED',
    OPENING: 'OPENING',
    OPEN: 'OPEN',
    CLOSING: 'CLOSING',
}

_ON_CHANNEL_CLEANUP_CB_KEY class-attribute instance-attribute

_ON_CHANNEL_CLEANUP_CB_KEY = '_on_channel_cleanup'

_MAX_RETAINED_CANCELLED_TAGS class-attribute instance-attribute

_MAX_RETAINED_CANCELLED_TAGS = 1024

channel_number instance-attribute

channel_number = channel_number

callbacks instance-attribute

callbacks = connection.callbacks

connection instance-attribute

connection = connection

flow_active instance-attribute

flow_active = True

_content_assembler instance-attribute

_content_assembler = ContentFrameAssembler()

_blocked instance-attribute

_blocked: deque = deque()

_blocking instance-attribute

_blocking: Any | None = None

_has_on_flow_callback instance-attribute

_has_on_flow_callback: bool = False

_cancelled instance-attribute

_cancelled: set = set()

_nowait_cancelled instance-attribute

_nowait_cancelled: deque = deque()

_consumers instance-attribute

_consumers: dict = {}

_consumers_with_noack instance-attribute

_consumers_with_noack: set = set()

_on_flowok_callback instance-attribute

_on_flowok_callback: Callable[..., Any] | None = None

_on_getok_callback instance-attribute

_on_getok_callback: Callable[..., Any] | None = None

_on_ack_nack_callback instance-attribute

_on_ack_nack_callback: _OnAckNackCallback | None = None

_on_openok_callback instance-attribute

_on_openok_callback: Callable[..., Any] | None = (
    on_open_callback
)

_state instance-attribute

_state: int = self.CLOSED

_closing_reason instance-attribute

_closing_reason = None
_cookie: object = None

consumer_tags property

consumer_tags: list[str]

Property method that returns a list of currently active consumers.

is_closed property

is_closed: bool

Returns True if the channel is closed.

is_closing property

is_closing: bool

Returns True if client-initiated closing of the channel is in progress.

is_open property

is_open: bool

Returns True if the channel is open.

is_opening property

is_opening: bool

Returns True if the channel is opening.

__init__

__init__(
    connection: Connection,
    channel_number: int,
    on_open_callback: _OnOpenCallback | None,
) -> None

Create a new instance of the Channel.

PARAMETER DESCRIPTION
connection

The connection

TYPE: Connection

channel_number

The channel number for this instance

TYPE: int

on_open_callback

The callback to call on channel open. The callback will be invoked with the Channel instance as its only argument.

TYPE: _OnOpenCallback | None

Source code in pika/channel.py
def __init__(self, connection: Connection, channel_number: int,
             on_open_callback: _OnOpenCallback | None) -> None:
    """
    Create a new instance of the Channel.

    :param connection: The connection
    :param channel_number: The channel number for this instance
    :param on_open_callback: The callback to call on channel open. The callback will be invoked
        with the `Channel` instance as its only argument.
    """
    if not isinstance(channel_number, int):
        raise exceptions.InvalidChannelNumber(channel_number)

    validators.rpc_completion_callback(on_open_callback)

    self.channel_number = channel_number
    self.callbacks = connection.callbacks
    self.connection = connection

    # Initially, flow is assumed to be active
    self.flow_active = True

    self._content_assembler = ContentFrameAssembler()

    self._blocked: deque = deque()
    self._blocking: Any | None = None
    self._has_on_flow_callback: bool = False
    self._cancelled: set = set()
    # Nowait-cancelled tags in cancellation order, bounding how many of
    # them `_cancelled` retains; see `_retain_cancelled_tag`.
    self._nowait_cancelled: deque = deque()
    self._consumers: dict = {}
    self._consumers_with_noack: set = set()
    self._on_flowok_callback: Callable[..., Any] | None = None
    self._on_getok_callback: Callable[..., Any] | None = None
    self._on_ack_nack_callback: _OnAckNackCallback | None = None
    self._on_openok_callback: Callable[..., Any] | None = on_open_callback
    self._state: int = self.CLOSED

    # We save the closing reason exception to be passed to on-channel-close
    # callback at closing of the channel. Exception representing the closing
    # reason; ChannelClosedByClient or ChannelClosedByBroker on controlled
    # close; otherwise another exception describing the reason for failure
    # (most likely connection failure).
    self._closing_reason = None  # type: None | Exception

    # opaque cookie value set by wrapper layer (e.g., BlockingConnection)
    # via _set_cookie
    self._cookie: object = None

__int__

__int__() -> int

Return the channel object as its channel number.

Source code in pika/channel.py
def __int__(self) -> int:
    """Return the channel object as its channel number."""
    return self.channel_number

__repr__

__repr__() -> str
Source code in pika/channel.py
@override
def __repr__(self) -> str:
    return f'<{self.__class__.__name__} number={self.channel_number} {self._STATE_NAMES[self._state]} conn={self.connection!r}>'

add_callback

add_callback(
    callback: Callable[..., Any],
    replies: Sequence[type[Method]],
    one_shot: bool = True,
) -> None

Pass in a callback handler and a list replies from the RabbitMQ broker which you'd like the callback notified of. Callbacks should allow for the frame parameter to be passed in.

PARAMETER DESCRIPTION
callback

The callback to call

TYPE: Callable[..., Any]

replies

The replies to get a callback for

TYPE: Sequence[type[Method]]

one_shot

Only handle the first type callback

TYPE: bool DEFAULT: True

Source code in pika/channel.py
def add_callback(self,
                 callback: Callable[..., Any],
                 replies: Sequence[type[amqp_object.Method]],
                 one_shot: bool = True) -> None:
    """
    Pass in a callback handler and a list replies from the RabbitMQ broker which you'd like the
    callback notified of. Callbacks should allow for the frame parameter to be passed in.

    :param callback: The callback to call
    :param replies: The replies to get a callback for
    :param one_shot: Only handle the first type callback
    """
    for reply in replies:
        self.callbacks.add(self.channel_number, reply, callback, one_shot)

add_on_cancel_callback

add_on_cancel_callback(callback: _OnCancelCallback) -> None

Pass a callback function that will be called when the basic_cancel is sent by the server. The callback function should receive a frame parameter.

PARAMETER DESCRIPTION
callback

The callback to call on Basic.Cancel from broker

TYPE: _OnCancelCallback

Source code in pika/channel.py
def add_on_cancel_callback(self, callback: _OnCancelCallback) -> None:
    """
    Pass a callback function that will be called when the basic_cancel is sent by the server.
    The callback function should receive a frame parameter.

    :param callback: The callback to call on Basic.Cancel from broker
    """
    self.callbacks.add(self.channel_number, spec.Basic.Cancel, callback,
                       False)

add_on_close_callback

add_on_close_callback(callback: _OnCloseCallback) -> None

Pass a callback function that will be called when the channel is closed.

The callback function will receive the channel and an exception describing why the channel was closed.

If the channel is closed by broker via Channel.Close, the callback will receive ChannelClosedByBroker as the reason.

If graceful user-initiated channel closing completes successfully ( either directly of indirectly by closing a connection containing the channel) and closing concludes gracefully without Channel.Close from the broker and without loss of connection, the callback will receive ChannelClosedByClient exception as reason.

If channel was closed due to loss of connection, the callback will receive another exception type describing the failure.

PARAMETER DESCRIPTION
callback

The callback, having the signature: callback(Channel, Exception reason)

TYPE: _OnCloseCallback

Source code in pika/channel.py
def add_on_close_callback(self, callback: _OnCloseCallback) -> None:
    """
    Pass a callback function that will be called when the channel is closed.

    The callback function will receive the channel and an exception describing why the channel
    was closed.

    If the channel is closed by broker via Channel.Close, the callback will receive
    `ChannelClosedByBroker` as the reason.

    If graceful user-initiated channel closing completes successfully ( either directly of
    indirectly by closing a connection containing the channel) and closing concludes gracefully
    without Channel.Close from the broker and without loss of connection, the callback will
    receive `ChannelClosedByClient` exception as reason.

    If channel was closed due to loss of connection, the callback will receive another exception
    type describing the failure.

    :param callback: The callback, having the signature: callback(Channel, Exception reason)
    """
    self.callbacks.add(self.channel_number, '_on_channel_close', callback,
                       False, self)

add_on_flow_callback

add_on_flow_callback(callback: _OnFlowCallback) -> None

Pass a callback function that will be called when Channel.Flow is called by the remote server. Note that newer versions of RabbitMQ will not issue this but instead use TCP backpressure.

PARAMETER DESCRIPTION
callback

The callback function

TYPE: _OnFlowCallback

Source code in pika/channel.py
def add_on_flow_callback(self, callback: _OnFlowCallback) -> None:
    """
    Pass a callback function that will be called when Channel.Flow is called by the remote
    server. Note that newer versions of RabbitMQ will not issue this but instead use TCP
    backpressure.

    :param callback: The callback function
    """
    self._has_on_flow_callback = True
    self.callbacks.add(self.channel_number, spec.Channel.Flow, callback,
                       False)

add_on_return_callback

add_on_return_callback(callback: _OnReturnCallback) -> None

Pass a callback function that will be called when basic_publish is sent a message that has been rejected and returned by the server.

PARAMETER DESCRIPTION
callback

The function to call, having the signature callback(channel, method, properties, body) where - channel: pika.channel.Channel - method: pika.spec.Basic.Return - properties: pika.spec.BasicProperties - body: bytes

TYPE: _OnReturnCallback

Source code in pika/channel.py
def add_on_return_callback(self, callback: _OnReturnCallback) -> None:
    """
    Pass a callback function that will be called when basic_publish is sent a message that has
    been rejected and returned by the server.

    :param callback: The function to call, having the signature
                            callback(channel, method, properties, body)
                            where
                            - channel: pika.channel.Channel
                            - method: pika.spec.Basic.Return
                            - properties: pika.spec.BasicProperties
                            - body: bytes
    """
    self.callbacks.add(self.channel_number, '_on_return', callback, False)

remove_callback

remove_callback(
    callback: Callable[..., Any],
    replies: Sequence[type[Method]] | None = None,
) -> bool

Remove a callback previously registered via :meth:add_callback.

Mirrors :meth:add_callback: the callback is matched by identity and removed from each reply key it is registered under. If replies is None, the callback is removed from every reply key it is currently registered under.

PARAMETER DESCRIPTION
callback

The callback to remove

TYPE: Callable[..., Any]

replies

The replies to remove the callback from, or None to remove it from every reply key it is registered under

TYPE: Sequence[type[Method]] | None DEFAULT: None

RETURNS DESCRIPTION
bool

True if at least one matching callback was removed

Source code in pika/channel.py
def remove_callback(
        self,
        callback: Callable[..., Any],
        replies: Sequence[type[amqp_object.Method]] | None = None) -> bool:
    """
    Remove a callback previously registered via :meth:`add_callback`.

    Mirrors :meth:`add_callback`: the callback is matched by identity and removed
    from each reply key it is registered under. If ``replies`` is ``None``, the
    callback is removed from every reply key it is currently registered under.

    :param callback: The callback to remove
    :param replies: The replies to remove the callback from, or ``None`` to
        remove it from every reply key it is registered under
    :returns: ``True`` if at least one matching callback was removed
    """
    reply_keys = (self.callbacks.keys(self.channel_number)
                  if replies is None else replies)
    removed = False
    for reply in reply_keys:
        if self.callbacks.remove_matching(self.channel_number, reply,
                                          lambda cb: cb == callback):
            removed = True
    return removed

remove_on_cancel_callback

remove_on_cancel_callback(
    callback: _OnCancelCallback,
) -> bool

Remove a callback registered via :meth:add_on_cancel_callback.

PARAMETER DESCRIPTION
callback

The callback to remove

TYPE: _OnCancelCallback

RETURNS DESCRIPTION
bool

True if the callback was removed, False if it was absent

Source code in pika/channel.py
def remove_on_cancel_callback(self, callback: _OnCancelCallback) -> bool:
    """
    Remove a callback registered via :meth:`add_on_cancel_callback`.

    :param callback: The callback to remove
    :returns:``True`` if the callback was removed, ``False`` if it was absent
    """
    return self.callbacks.remove_matching(self.channel_number,
                                          spec.Basic.Cancel,
                                          lambda cb: cb == callback)

remove_on_close_callback

remove_on_close_callback(
    callback: _OnCloseCallback,
) -> bool

Remove a callback registered via :meth:add_on_close_callback.

PARAMETER DESCRIPTION
callback

The callback to remove

TYPE: _OnCloseCallback

RETURNS DESCRIPTION
bool

True if the callback was removed, False if it was absent

Source code in pika/channel.py
def remove_on_close_callback(self, callback: _OnCloseCallback) -> bool:
    """
    Remove a callback registered via :meth:`add_on_close_callback`.

    :param callback: The callback to remove
    :returns:``True`` if the callback was removed, ``False`` if it was absent
    """
    return self.callbacks.remove_matching(self.channel_number,
                                          '_on_channel_close',
                                          lambda cb: cb == callback)

remove_on_flow_callback

remove_on_flow_callback(callback: _OnFlowCallback) -> bool

Remove a callback registered via :meth:add_on_flow_callback.

PARAMETER DESCRIPTION
callback

The callback to remove

TYPE: _OnFlowCallback

RETURNS DESCRIPTION
bool

True if the callback was removed, False if it was absent

Source code in pika/channel.py
def remove_on_flow_callback(self, callback: _OnFlowCallback) -> bool:
    """
    Remove a callback registered via :meth:`add_on_flow_callback`.

    :param callback: The callback to remove
    :returns:``True`` if the callback was removed, ``False`` if it was absent
    """
    return self.callbacks.remove_matching(self.channel_number,
                                          spec.Channel.Flow,
                                          lambda cb: cb == callback)

remove_on_return_callback

remove_on_return_callback(
    callback: _OnReturnCallback,
) -> bool

Remove a callback registered via :meth:add_on_return_callback.

PARAMETER DESCRIPTION
callback

The callback to remove

TYPE: _OnReturnCallback

RETURNS DESCRIPTION
bool

True if the callback was removed, False if it was absent

Source code in pika/channel.py
def remove_on_return_callback(self, callback: _OnReturnCallback) -> bool:
    """
    Remove a callback registered via :meth:`add_on_return_callback`.

    :param callback: The callback to remove
    :returns:``True`` if the callback was removed, ``False`` if it was absent
    """
    return self.callbacks.remove_matching(self.channel_number, '_on_return',
                                          lambda cb: cb == callback)

basic_ack

basic_ack(
    delivery_tag: int = 0, multiple: bool = False
) -> None

Acknowledge one or more messages.

When sent by the client, this method acknowledges one or more messages delivered via the Deliver or Get-Ok methods. When sent by server, this method acknowledges one or more messages published with the Publish method on a channel in confirm mode. The acknowledgement can be for a single message or a set of messages up to and including a specific message.

PARAMETER DESCRIPTION
delivery_tag

int/long The server-assigned delivery tag

TYPE: int DEFAULT: 0

multiple

If set to True, the delivery tag is treated as "up to and including", so that multiple messages can be acknowledged with a single method. If set to False, the delivery tag refers to a single message. If the multiple field is 1, and the delivery tag is zero, this indicates acknowledgement of all outstanding messages.

TYPE: bool DEFAULT: False

Source code in pika/channel.py
def basic_ack(self, delivery_tag: int = 0, multiple: bool = False) -> None:
    """
    Acknowledge one or more messages.

    When sent by the client, this method acknowledges one or more messages delivered via the
    Deliver or Get-Ok methods. When sent by server, this method acknowledges one or more
    messages published with the Publish method on a channel in confirm mode. The acknowledgement
    can be for a single message or a set of messages up to and including a specific message.

    :param delivery_tag: int/long The server-assigned delivery tag
    :param multiple: If set to True, the delivery tag is treated as "up to and including", so
        that multiple messages can be acknowledged with a single method. If set to False, the
        delivery tag refers to a single message. If the multiple field is 1, and the delivery
        tag is zero, this indicates acknowledgement of all outstanding messages.
    """
    self._raise_if_not_open()
    return self._send_method(spec.Basic.Ack(delivery_tag, multiple))

basic_cancel

basic_cancel(
    consumer_tag: str = '',
    callback: _OnBasicCancelCallback | None = None,
) -> None

This method cancels a consumer.

This does not affect already delivered messages, but it does mean the server will not send any more messages for that consumer. The client may receive an arbitrary number of messages in between sending the cancel method and receiving the cancel-ok reply. It may also be sent from the server to the client in the event of the consumer being unexpectedly cancelled (i.e. cancelled for any reason other than the server receiving the corresponding basic.cancel from the client). This allows clients to be notified of the loss of consumers due to events such as queue deletion.

A cancelled consumer's tag is retained so that a delivery already in flight when the cancel was sent is rejected rather than left unacknowledged. A cancel that expects a Basic.CancelOk retires its own entry on arrival; a nowait cancel has no reply to retire it, so its tag is kept only until _MAX_RETAINED_CANCELLED_TAGS later nowait cancels displace it (see _retain_cancelled_tag). Past that point its retention lapses: a straggling delivery for it is logged as unexpected and left unacknowledged rather than rejected, and the tag may be reused by basic_consume, so reusing the same explicit consumer_tag risks a delivery for the old consumer reaching the new one. The cap is a generous approximation of the broker's in-flight window, so this only bites under extreme nowait-cancel churn.

PARAMETER DESCRIPTION
consumer_tag

Identifier for the consumer

TYPE: str DEFAULT: ''

callback

callback(pika.frame.Method) for method Basic.CancelOk. If None, do not expect a Basic.CancelOk response, otherwise, callback must be callable

TYPE: _OnBasicCancelCallback | None DEFAULT: None

RAISES DESCRIPTION
ValueError
Source code in pika/channel.py
def basic_cancel(self,
                 consumer_tag: str = '',
                 callback: _OnBasicCancelCallback | None = None) -> None:
    """
    This method cancels a consumer.

    This does not affect already delivered messages, but it does mean the server will not send
    any more messages for that consumer. The client may receive an arbitrary number of messages
    in between sending the cancel method and receiving the cancel-ok reply. It may also be sent
    from the server to the client in the event of the consumer being unexpectedly cancelled
    (i.e. cancelled for any reason other than the server receiving the corresponding
    basic.cancel from the client). This allows clients to be notified of the loss of consumers
    due to events such as queue deletion.

    A cancelled consumer's tag is retained so that a delivery already in flight when the cancel
    was sent is rejected rather than left unacknowledged. A cancel that expects a Basic.CancelOk
    retires its own entry on arrival; a nowait cancel has no reply to retire it, so its tag is
    kept only until `_MAX_RETAINED_CANCELLED_TAGS` later nowait cancels displace it (see
    `_retain_cancelled_tag`). Past that point its retention lapses: a straggling delivery for it
    is logged as unexpected and left unacknowledged rather than rejected, and the tag may be
    reused by `basic_consume`, so reusing the same explicit consumer_tag risks a delivery for
    the old consumer reaching the new one. The cap is a generous approximation of the broker's
    in-flight window, so this only bites under extreme nowait-cancel churn.

    :param consumer_tag: Identifier for the consumer
    :param callback: callback(pika.frame.Method) for method Basic.CancelOk. If None, do not
        expect a Basic.CancelOk response, otherwise, callback must be callable
    :raises ValueError:
    """
    validators.require_string(consumer_tag, 'consumer_tag')
    self._raise_if_not_open()
    nowait = validators.rpc_completion_callback(callback)

    if consumer_tag in self._cancelled:
        # We check for cancelled first, because basic_cancel removes
        # consumers closed with nowait from self._consumers
        LOGGER.warning('basic_cancel - consumer is already cancelling: %s',
                       consumer_tag)
        return

    if consumer_tag not in self._consumers:
        # Could be cancelled by user or broker earlier
        LOGGER.warning('basic_cancel - consumer not found: %s',
                       consumer_tag)
        return

    LOGGER.debug('Cancelling consumer: %s (nowait=%s)', consumer_tag,
                 nowait)

    if nowait:
        # This is our last opportunity while the channel is open to remove
        # this consumer callback and help gc.
        del self._consumers[consumer_tag]

    if callback is not None:
        self.callbacks.add(self.channel_number, spec.Basic.CancelOk,
                           callback)

    self._cancelled.add(consumer_tag)

    if nowait:
        self._retain_cancelled_tag(consumer_tag)

    self._rpc(spec.Basic.Cancel(consumer_tag=consumer_tag, nowait=nowait),
              self._on_cancelok if not nowait else None,
              [(spec.Basic.CancelOk, {
                  'consumer_tag': consumer_tag
              })] if not nowait else [])

basic_consume

basic_consume(
    queue: str,
    on_message_callback: _OnMessageCallback,
    auto_ack: bool = False,
    exclusive: bool = False,
    consumer_tag: str | None = None,
    arguments: dict[str, Any] | None = None,
    callback: _OnBasicConsumeCallback | None = None,
) -> str

Sends the AMQP 0-9-1 command Basic.Consume to the broker and binds messages for the consumer_tag to the consumer callback. If you do not pass in a consumer_tag, one will be automatically generated for you. Returns the consumer tag.

For more information on basic_consume, see: Tutorial 2 at https://www.rabbitmq.com/getstarted.html https://www.rabbitmq.com/confirms.html https://www.rabbitmq.com/amqp-0-9-1-reference.html#basic.consume

PARAMETER DESCRIPTION
queue

The queue to consume from. Use the empty string to specify the most recent server-named queue for this channel

TYPE: str

on_message_callback

The function to call when consuming with the signature on_message_callback(channel, method, properties, body), where - channel: pika.channel.Channel - method: pika.spec.Basic.Deliver - properties: pika.spec.BasicProperties - body: bytes

TYPE: _OnMessageCallback

auto_ack

if set to True, automatic acknowledgement mode will be used (see https://www.rabbitmq.com/confirms.html). This corresponds with the 'no_ack' parameter in the basic.consume AMQP 0.9.1 method

TYPE: bool DEFAULT: False

exclusive

Don't allow other consumers on the queue

TYPE: bool DEFAULT: False

consumer_tag

Specify your own consumer tag

TYPE: str | None DEFAULT: None

arguments

Custom key/value pair arguments for the consumer

TYPE: dict[str, Any] | None DEFAULT: None

callback

callback(pika.frame.Method) for method Basic.ConsumeOk.

TYPE: _OnBasicConsumeCallback | None DEFAULT: None

RETURNS DESCRIPTION
str

Consumer tag which may be used to cancel the consumer.

RAISES DESCRIPTION
ValueError
Source code in pika/channel.py
def basic_consume(self,
                  queue: str,
                  on_message_callback: _OnMessageCallback,
                  auto_ack: bool = False,
                  exclusive: bool = False,
                  consumer_tag: str | None = None,
                  arguments: dict[str, Any] | None = None,
                  callback: _OnBasicConsumeCallback | None = None) -> str:
    """
    Sends the AMQP 0-9-1 command Basic.Consume to the broker and binds messages for the
    consumer_tag to the consumer callback. If you do not pass in a consumer_tag, one will be
    automatically generated for you. Returns the consumer tag.

    For more information on basic_consume, see:
    Tutorial 2 at https://www.rabbitmq.com/getstarted.html
    https://www.rabbitmq.com/confirms.html
    https://www.rabbitmq.com/amqp-0-9-1-reference.html#basic.consume

    :param queue: The queue to consume from. Use the empty string to
        specify the most recent server-named queue for this channel
    :param on_message_callback: The function to call when
        consuming with the signature
        on_message_callback(channel, method, properties, body), where
        - channel: pika.channel.Channel
        - method: pika.spec.Basic.Deliver
        - properties: pika.spec.BasicProperties
        - body: bytes
    :param auto_ack: if set to True, automatic acknowledgement mode
        will be used (see https://www.rabbitmq.com/confirms.html).
        This corresponds with the 'no_ack' parameter in the basic.consume
        AMQP 0.9.1 method
    :param exclusive: Don't allow other consumers on the queue
    :param consumer_tag: Specify your own consumer tag
    :param arguments: Custom key/value pair arguments for the consumer
    :param callback: callback(pika.frame.Method) for method
      Basic.ConsumeOk.
    :returns: Consumer tag which may be used to cancel the consumer.
    :raises ValueError:
    """
    validators.require_string(queue, 'queue')
    validators.require_callback(on_message_callback)
    self._raise_if_not_open()
    validators.rpc_completion_callback(callback)

    # If a consumer tag was not passed, create one
    if not consumer_tag:
        consumer_tag = self._generate_consumer_tag()

    if consumer_tag in self._consumers or consumer_tag in self._cancelled:
        raise exceptions.DuplicateConsumerTag(consumer_tag)

    if auto_ack:
        self._consumers_with_noack.add(consumer_tag)

    self._consumers[consumer_tag] = on_message_callback

    rpc_callback: Callable[
        ...,
        Any] | None = self._on_eventok if callback is None else callback

    self._rpc(
        spec.Basic.Consume(queue=queue,
                           consumer_tag=consumer_tag,
                           no_ack=auto_ack,
                           exclusive=exclusive,
                           arguments=arguments or {}), rpc_callback,
        [(spec.Basic.ConsumeOk, {
            'consumer_tag': consumer_tag
        })])

    return consumer_tag

_generate_consumer_tag

_generate_consumer_tag() -> str

Generate a consumer tag.

NOTE: this protected method may be called by derived classes

RETURNS DESCRIPTION
str

consumer tag

Source code in pika/channel.py
def _generate_consumer_tag(self) -> str:
    """
    Generate a consumer tag.

    NOTE: this protected method may be called by derived classes

    :returns: consumer tag
    """
    return f'ctag{self.channel_number}.{uuid.uuid4().hex}'

basic_get

basic_get(
    queue: str,
    callback: _OnBasicGetCallback,
    auto_ack: bool = False,
) -> None

Get a single message from the AMQP broker.

If you want to be notified of Basic.GetEmpty, use the Channel.add_callback method adding your Basic.GetEmpty callback which should expect only one parameter, frame. Due to implementation details, this cannot be called a second time until the callback is executed. For more information on basic_get and its parameters, see:

https://www.rabbitmq.com/amqp-0-9-1-reference.html#basic.get

PARAMETER DESCRIPTION
queue

The queue from which to get a message. Use the empty string to specify the most recent server-named queue for this channel

TYPE: str

callback

The callback to call with a message that has the signature callback(channel, method, properties, body), where: - channel: pika.channel.Channel - method: pika.spec.Basic.GetOk - properties: pika.spec.BasicProperties - body: bytes

TYPE: _OnBasicGetCallback

auto_ack

Tell the broker to not expect a reply

TYPE: bool DEFAULT: False

RAISES DESCRIPTION
ValueError
Source code in pika/channel.py
def basic_get(self,
              queue: str,
              callback: _OnBasicGetCallback,
              auto_ack: bool = False) -> None:
    """
    Get a single message from the AMQP broker.

    If you want to be notified of Basic.GetEmpty, use the Channel.add_callback method
    adding your Basic.GetEmpty callback which should expect only one
    parameter, frame. Due to implementation details, this cannot be called
    a second time until the callback is executed.  For more information on
    basic_get and its parameters, see:

    https://www.rabbitmq.com/amqp-0-9-1-reference.html#basic.get

    :param queue: The queue from which to get a message. Use the empty
        string to specify the most recent server-named queue for this
        channel
    :param callback: The callback to call with a message that has
        the signature callback(channel, method, properties, body), where:
        - channel: pika.channel.Channel
        - method: pika.spec.Basic.GetOk
        - properties: pika.spec.BasicProperties
        - body: bytes
    :param auto_ack: Tell the broker to not expect a reply
    :raises ValueError:
    """
    validators.require_string(queue, 'queue')
    validators.require_callback(callback)
    if self._on_getok_callback is not None:
        raise exceptions.DuplicateGetOkCallback()
    self._on_getok_callback = callback

    # TODO Strangely, not using _rpc for the synchronous Basic.Get. Would
    # need to extend _rpc to handle Basic.GetOk method, header, and body
    # frames (or similar)
    self._send_method(spec.Basic.Get(queue=queue, no_ack=auto_ack))

basic_nack

basic_nack(
    delivery_tag: int = 0,
    multiple: bool = False,
    requeue: bool = True,
) -> None

This method allows a client to reject one or more incoming messages.

It can be used to interrupt and cancel large incoming messages, or return untreatable messages to their original queue.

PARAMETER DESCRIPTION
delivery_tag

int/long The server-assigned delivery tag

TYPE: int DEFAULT: 0

multiple

If set to True, the delivery tag is treated as "up to and including", so that multiple messages can be acknowledged with a single method. If set to False, the delivery tag refers to a single message. If the multiple field is 1, and the delivery tag is zero, this indicates acknowledgement of all outstanding messages.

TYPE: bool DEFAULT: False

requeue

If requeue is true, the server will attempt to requeue the message. If requeue is false or the requeue attempt fails the messages are discarded or dead- lettered.

TYPE: bool DEFAULT: True

Source code in pika/channel.py
def basic_nack(self,
               delivery_tag: int = 0,
               multiple: bool = False,
               requeue: bool = True) -> None:
    """
    This method allows a client to reject one or more incoming messages.

    It can be used to interrupt and cancel large incoming messages, or return untreatable
    messages to their original queue.

    :param delivery_tag: int/long The server-assigned delivery tag
    :param multiple: If set to True, the delivery tag is treated as "up to and including", so
        that multiple messages can be acknowledged with a single method. If set to False, the
        delivery tag refers to a single message. If the multiple field is 1, and the delivery
        tag is zero, this indicates acknowledgement of all outstanding messages.
    :param requeue: If requeue is true, the server will attempt to requeue the message. If
        requeue is false or the requeue attempt fails the messages are discarded or dead-
        lettered.
    """
    self._raise_if_not_open()
    return self._send_method(
        spec.Basic.Nack(delivery_tag, multiple, requeue))

basic_publish

basic_publish(
    exchange: str,
    routing_key: str,
    body: bytes,
    properties: BasicProperties | None = None,
    mandatory: bool = False,
) -> None

Publish to the channel with the given exchange, routing key and body.

For more information on basic_publish and what the parameters do, see:

https://www.rabbitmq.com/amqp-0-9-1-reference.html#basic.publish

PARAMETER DESCRIPTION
exchange

The exchange to publish to

TYPE: str

routing_key

The routing key to bind on

TYPE: str

body

The message body

TYPE: bytes

properties

Basic.properties

TYPE: BasicProperties | None DEFAULT: None

mandatory

The mandatory flag

TYPE: bool DEFAULT: False

Source code in pika/channel.py
def basic_publish(self,
                  exchange: str,
                  routing_key: str,
                  body: bytes,
                  properties: spec.BasicProperties | None = None,
                  mandatory: bool = False) -> None:
    """
    Publish to the channel with the given exchange, routing key and body.

    For more information on basic_publish and what the parameters do, see:

    https://www.rabbitmq.com/amqp-0-9-1-reference.html#basic.publish

    :param exchange: The exchange to publish to
    :param routing_key: The routing key to bind on
    :param body: The message body
    :param properties: Basic.properties
    :param mandatory: The mandatory flag
    """
    self._raise_if_not_open()
    body = as_bytes(body)
    properties = properties or spec.BasicProperties()
    self._send_method(
        spec.Basic.Publish(exchange=exchange,
                           routing_key=routing_key,
                           mandatory=mandatory), (properties, body))

basic_qos

basic_qos(
    prefetch_size: int = 0,
    prefetch_count: int = 0,
    global_qos: bool = False,
    callback: _OnBasicQosCallback | None = None,
) -> None

Specify quality of service.

This method requests a specific quality of service. The client can request that messages 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. The QoS can be applied separately to each new consumer on channel or shared across all consumers on the channel. Prefetching gives a performance improvement.

PARAMETER DESCRIPTION
prefetch_size

This field specifies the prefetch window size. 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 into other prefetch limits). May be set to zero, meaning "no specific limit", although other prefetch limits may still apply. The prefetch-size is ignored by consumers who have enabled the no-ack option.

TYPE: int DEFAULT: 0

prefetch_count

Specifies a prefetch window in terms of whole messages. This field may be used in combination with the prefetch-size field; a message will only be sent in advance if both prefetch windows (and those at the channel and connection level) allow it. The prefetch-count is ignored by consumers who have enabled the no-ack option.

TYPE: int DEFAULT: 0

global_qos

Should the QoS be shared across all consumers on the channel.

TYPE: bool DEFAULT: False

callback

The callback to call for Basic.QosOk response

TYPE: _OnBasicQosCallback | None DEFAULT: None

RETURNS DESCRIPTION
None

None. Method frame from the Basic.Qos-ok response is delivered to callback when provided.

RAISES DESCRIPTION
ValueError
Source code in pika/channel.py
def basic_qos(self,
              prefetch_size: int = 0,
              prefetch_count: int = 0,
              global_qos: bool = False,
              callback: _OnBasicQosCallback | None = None) -> None:
    """
    Specify quality of service.

    This method requests a specific quality of service. The client can request that messages 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. The QoS can be
    applied separately to each new consumer on channel or shared across all consumers on the
    channel. Prefetching gives a performance improvement.

    :param prefetch_size: This field specifies the prefetch window size. 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 into other prefetch limits). May be set to zero, meaning "no specific
        limit", although other prefetch limits may still apply. The prefetch-size is ignored by
        consumers who have enabled the no-ack option.
    :param prefetch_count: Specifies a prefetch window in terms of whole messages. This field
        may be used in combination with the prefetch-size field; a message will only be sent in
        advance if both prefetch windows (and those at the channel and connection level) allow
        it. The prefetch-count is ignored by consumers who have enabled the no-ack option.
    :param global_qos: Should the QoS be shared across all consumers on the channel.
    :param callback: The callback to call for Basic.QosOk response
    :returns:``None``. Method frame from the Basic.Qos-ok response is delivered to ``callback``
        when provided.
    :raises ValueError:
    """
    self._raise_if_not_open()
    validators.rpc_completion_callback(callback)
    validators.zero_or_greater('prefetch_size', prefetch_size)
    validators.zero_or_greater('prefetch_count', prefetch_count)
    return self._rpc(
        spec.Basic.Qos(prefetch_size, prefetch_count, global_qos), callback,
        [spec.Basic.QosOk])

basic_reject

basic_reject(
    delivery_tag: int = 0, requeue: bool = True
) -> None

Reject an incoming message.

This method allows a client to reject a message. It can be used to interrupt and cancel large incoming messages, or return untreatable messages to their original queue.

PARAMETER DESCRIPTION
delivery_tag

int/long The server-assigned delivery tag

TYPE: int DEFAULT: 0

requeue

If requeue is true, the server will attempt to requeue the message. If requeue is false or the requeue attempt fails the messages are discarded or dead- lettered.

TYPE: bool DEFAULT: True

RAISES DESCRIPTION
TypeError
Source code in pika/channel.py
def basic_reject(self, delivery_tag: int = 0, requeue: bool = True) -> None:
    """
    Reject an incoming message.

    This method allows a client to reject a message. It can be used to interrupt and cancel
    large incoming messages, or return untreatable messages to their original queue.

    :param delivery_tag: int/long The server-assigned delivery tag
    :param requeue: If requeue is true, the server will attempt to requeue the message. If
        requeue is false or the requeue attempt fails the messages are discarded or dead-
        lettered.
    :raises TypeError:
    """
    self._raise_if_not_open()
    if not isinstance(delivery_tag, int):
        raise TypeError('delivery_tag must be an integer')
    return self._send_method(spec.Basic.Reject(delivery_tag, requeue))

basic_recover

basic_recover(
    requeue: bool = False,
    callback: _OnBasicRecoverCallback | None = None,
) -> None

This method asks the server to redeliver all unacknowledged messages on a specified channel. Zero or more messages may be redelivered. This method replaces the asynchronous Recover.

PARAMETER DESCRIPTION
requeue

If False, the message will be redelivered to the original recipient. If True, the server will attempt to requeue the message, potentially then delivering it to an alternative subscriber.

TYPE: bool DEFAULT: False

callback

callback(pika.frame.Method) for method Basic.RecoverOk

TYPE: _OnBasicRecoverCallback | None DEFAULT: None

RETURNS DESCRIPTION
None

None. Method frame from the Basic.Recover-ok response is delivered to callback when provided.

RAISES DESCRIPTION
ValueError
Source code in pika/channel.py
def basic_recover(self,
                  requeue: bool = False,
                  callback: _OnBasicRecoverCallback | None = None) -> None:
    """
    This method asks the server to redeliver all unacknowledged messages on a specified channel.
    Zero or more messages may be redelivered. This method replaces the asynchronous Recover.

    :param requeue: If False, the message will be redelivered to the original recipient. If
        True, the server will attempt to requeue the message, potentially then delivering it to
        an alternative subscriber.
    :param callback: callback(pika.frame.Method) for method Basic.RecoverOk
    :returns:``None``. Method frame from the Basic.Recover-ok response is delivered to
        ``callback`` when provided.
    :raises ValueError:
    """
    self._raise_if_not_open()
    validators.rpc_completion_callback(callback)
    return self._rpc(spec.Basic.Recover(requeue), callback,
                     [spec.Basic.RecoverOk])

close

close(
    reply_code: int = 0, reply_text: str = 'Normal shutdown'
) -> None

Invoke a graceful shutdown of the channel with the AMQP Broker.

If channel is OPENING, transition to CLOSING and suppress the incoming Channel.OpenOk, if any.

PARAMETER DESCRIPTION
reply_code

The reason code to send to broker

TYPE: int DEFAULT: 0

reply_text

The reason text to send to broker

TYPE: str DEFAULT: 'Normal shutdown'

RAISES DESCRIPTION
ChannelWrongStateError

if channel is closed or closing

Source code in pika/channel.py
def close(self,
          reply_code: int = 0,
          reply_text: str = 'Normal shutdown') -> None:
    """
    Invoke a graceful shutdown of the channel with the AMQP Broker.

    If channel is OPENING, transition to CLOSING and suppress the incoming Channel.OpenOk, if
    any.

    :param reply_code: The reason code to send to broker
    :param reply_text: The reason text to send to broker
    :raises ChannelWrongStateError: if channel is closed or closing
    """
    if self.is_closed or self.is_closing:
        # Whoever is calling `close` might expect the on-channel-close-cb
        # to be called, which won't happen when it's already closed.
        self._raise_if_not_open()

    # If channel is OPENING, we will transition it to CLOSING state,
    # causing the _on_openok method to suppress the OPEN state transition
    # and the on-channel-open-callback

    LOGGER.info('Closing channel (%s): %r on %s', reply_code, reply_text,
                self)

    # Save the reason info so that we may use it in the '_on_channel_close'
    # callback processing
    self._closing_reason = exceptions.ChannelClosedByClient(
        reply_code, reply_text)

    for consumer_tag in list(self._consumers.keys()):
        if consumer_tag not in self._cancelled:
            self.basic_cancel(consumer_tag=consumer_tag)

    # Change state after cancelling consumers to avoid
    # ChannelWrongStateError exception from basic_cancel
    self._set_state(self.CLOSING)

    self._rpc(spec.Channel.Close(reply_code, reply_text, 0, 0),
              self._on_closeok, [spec.Channel.CloseOk])

confirm_delivery

confirm_delivery(
    ack_nack_callback: _OnAckNackCallback,
    callback: _OnConfirmDeliveryCallback | None = None,
) -> None

Turn on Confirm mode in the channel.

Pass in a callback to be notified by the Broker when a message has been confirmed as received or rejected (Basic.Ack, Basic.Nack) from the broker to the publisher.

For more information see: https://www.rabbitmq.com/confirms.html

PARAMETER DESCRIPTION
ack_nack_callback

Required callback for delivery confirmations that has the following signature: callback(pika.frame.Method), where method_frame contains either method spec.Basic.Ack or spec.Basic.Nack.

TYPE: _OnAckNackCallback

callback

callback(pika.frame.Method) for method Confirm.SelectOk

TYPE: _OnConfirmDeliveryCallback | None DEFAULT: None

RAISES DESCRIPTION
TypeError

if ack_nack_callback is not callable

.. note:: Calling this method more than once on the same channel replaces the previously registered ack_nack_callback rather than adding an additional one. Only the most recently registered callback receives Basic.Ack/Basic.Nack notifications.

Source code in pika/channel.py
def confirm_delivery(
        self,
        ack_nack_callback: _OnAckNackCallback,
        callback: _OnConfirmDeliveryCallback | None = None) -> None:
    """
    Turn on Confirm mode in the channel.

    Pass in a callback to be notified by the Broker when a message has been confirmed as received or
    rejected (Basic.Ack, Basic.Nack) from the broker to the publisher.

    For more information see:
        https://www.rabbitmq.com/confirms.html

    :param ack_nack_callback: Required callback for delivery
        confirmations that has the following signature:
        callback(pika.frame.Method), where method_frame contains
        either method `spec.Basic.Ack` or `spec.Basic.Nack`.
    :param callback: callback(pika.frame.Method) for method
        Confirm.SelectOk
    :raises TypeError: if `ack_nack_callback` is not callable

    .. note::
        Calling this method more than once on the same channel replaces
        the previously registered ``ack_nack_callback`` rather than adding
        an additional one. Only the most recently registered callback
        receives ``Basic.Ack``/``Basic.Nack`` notifications.
    """
    if not callable(ack_nack_callback):
        # confirm_deliver requires a callback; it's meaningless
        # without a user callback to receive Basic.Ack/Basic.Nack notifications
        raise TypeError('confirm_delivery requires a callback '
                        'to receive Basic.Ack/Basic.Nack notifications')

    self._raise_if_not_open()
    nowait = validators.rpc_completion_callback(callback)

    if not (self.connection.publisher_confirms and
            self.connection.basic_nack):
        raise exceptions.MethodNotImplemented(
            'Confirm.Select not Supported by Server')

    # Replace any previously registered ack/nack callback so repeated
    # calls don't stack listeners and fire stale callbacks (see #1602).
    if self._on_ack_nack_callback is not None:
        self.callbacks.remove(self.channel_number, spec.Basic.Ack,
                              self._on_ack_nack_callback)
        self.callbacks.remove(self.channel_number, spec.Basic.Nack,
                              self._on_ack_nack_callback)

    # Add the ack and nack callback
    self.callbacks.add(self.channel_number, spec.Basic.Ack,
                       ack_nack_callback, False)
    self.callbacks.add(self.channel_number, spec.Basic.Nack,
                       ack_nack_callback, False)
    self._on_ack_nack_callback = ack_nack_callback

    self._rpc(spec.Confirm.Select(nowait), callback,
              [spec.Confirm.SelectOk] if not nowait else [])

exchange_bind

exchange_bind(
    destination: str,
    source: str,
    routing_key: str = '',
    arguments: dict[str, Any] | None = None,
    callback: _OnExchangeBindCallback | None = None,
) -> None

Bind an exchange to another exchange.

PARAMETER DESCRIPTION
destination

The destination exchange to bind

TYPE: str

source

The source exchange to bind to

TYPE: str

routing_key

The routing key to bind on

TYPE: str DEFAULT: ''

arguments

Custom key/value pair arguments for the binding

TYPE: dict[str, Any] | None DEFAULT: None

callback

callback(pika.frame.Method) for method Exchange.BindOk

TYPE: _OnExchangeBindCallback | None DEFAULT: None

RETURNS DESCRIPTION
None

None. Method frame from the Exchange.Bind-ok response is delivered to callback when synchronous (no ok frame in nowait mode).

RAISES DESCRIPTION
ValueError
Source code in pika/channel.py
def exchange_bind(self,
                  destination: str,
                  source: str,
                  routing_key: str = '',
                  arguments: dict[str, Any] | None = None,
                  callback: _OnExchangeBindCallback | None = None) -> None:
    """
    Bind an exchange to another exchange.

    :param destination: The destination exchange to bind
    :param source: The source exchange to bind to
    :param routing_key: The routing key to bind on
    :param arguments: Custom key/value pair arguments for the binding
    :param callback: callback(pika.frame.Method) for method Exchange.BindOk
    :returns:``None``. Method frame from the Exchange.Bind-ok response is delivered to
        ``callback`` when synchronous (no ok frame in nowait mode).
    :raises ValueError:
    """
    self._raise_if_not_open()
    validators.require_string(destination, 'destination')
    validators.require_string(source, 'source')
    nowait = validators.rpc_completion_callback(callback)
    return self._rpc(
        spec.Exchange.Bind(0, destination, source, routing_key, nowait,
                           arguments or {}), callback,
        [spec.Exchange.BindOk] if not nowait else [])

exchange_declare

exchange_declare(
    exchange: str,
    exchange_type: str = direct,
    passive: bool = False,
    durable: bool = False,
    auto_delete: bool = False,
    internal: bool = False,
    arguments: dict[str, Any] | None = None,
    callback: _OnExchangeDeclareCallback | None = None,
) -> None

This method creates an exchange if it does not already exist, and if the exchange exists, verifies that it is of the correct and expected class.

If passive set, the server will reply with Declare-Ok if the exchange already exists with the same name, and raise an error if not and if the exchange does not already exist, the server MUST raise a channel exception with reply code 404 (not found).

PARAMETER DESCRIPTION
exchange

The exchange name consists of a non-empty sequence of these characters: letters, digits, hyphen, underscore, period, or colon

TYPE: str

exchange_type

The exchange type to use

TYPE: str DEFAULT: direct

passive

Perform a declare or just check to see if it exists

TYPE: bool DEFAULT: False

durable

Survive a reboot of RabbitMQ

TYPE: bool DEFAULT: False

auto_delete

Remove when no more queues are bound to it

TYPE: bool DEFAULT: False

internal

Can only be published to by other exchanges

TYPE: bool DEFAULT: False

arguments

Custom key/value pair arguments for the exchange

TYPE: dict[str, Any] | None DEFAULT: None

callback

callback(pika.frame.Method) for method Exchange.DeclareOk

TYPE: _OnExchangeDeclareCallback | None DEFAULT: None

RETURNS DESCRIPTION
None

None. Method frame from the Exchange.Declare-ok response is delivered to callback when synchronous (no ok frame in nowait mode).

RAISES DESCRIPTION
ValueError
Source code in pika/channel.py
def exchange_declare(
        self,
        exchange: str,
        exchange_type: str = ExchangeType.direct,
        passive: bool = False,
        durable: bool = False,
        auto_delete: bool = False,
        internal: bool = False,
        arguments: dict[str, Any] | None = None,
        callback: _OnExchangeDeclareCallback | None = None) -> None:
    """
    This method creates an exchange if it does not already exist, and if the exchange exists,
    verifies that it is of the correct and expected class.

    If passive set, the server will reply with Declare-Ok if the exchange
    already exists with the same name, and raise an error if not and if the
    exchange does not already exist, the server MUST raise a channel
    exception with reply code 404 (not found).

    :param exchange: The exchange name consists of a non-empty sequence
        of these characters: letters, digits, hyphen, underscore, period,
        or colon
    :param exchange_type: The exchange type to use
    :param passive: Perform a declare or just check to see if it exists
    :param durable: Survive a reboot of RabbitMQ
    :param auto_delete: Remove when no more queues are bound to it
    :param internal: Can only be published to by other exchanges
    :param arguments: Custom key/value pair arguments for the exchange
    :param callback: callback(pika.frame.Method) for method Exchange.DeclareOk
    :returns: ``None``. Method frame from the Exchange.Declare-ok response is
        delivered to ``callback`` when synchronous (no ok frame in nowait
        mode).
    :raises ValueError:
    """
    validators.require_string(exchange, 'exchange')
    self._raise_if_not_open()
    nowait = validators.rpc_completion_callback(callback)
    if isinstance(exchange_type, Enum):
        exchange_type = exchange_type.value
    return self._rpc(
        spec.Exchange.Declare(0, exchange, exchange_type, passive, durable,
                              auto_delete, internal, nowait, arguments or
                              {}), callback,
        [spec.Exchange.DeclareOk] if not nowait else [])

exchange_delete

exchange_delete(
    exchange: str | None = None,
    if_unused: bool = False,
    callback: _OnExchangeDeleteCallback | None = None,
) -> None

Delete the exchange.

PARAMETER DESCRIPTION
exchange

The exchange name

TYPE: str | None DEFAULT: None

if_unused

only delete if the exchange is unused

TYPE: bool DEFAULT: False

callback

callback(pika.frame.Method) for method Exchange.DeleteOk

TYPE: _OnExchangeDeleteCallback | None DEFAULT: None

RETURNS DESCRIPTION
None

None. Method frame from the Exchange.Delete-ok response is delivered to callback when synchronous (no ok frame in nowait mode).

RAISES DESCRIPTION
ValueError
Source code in pika/channel.py
def exchange_delete(
        self,
        exchange: str | None = None,
        if_unused: bool = False,
        callback: _OnExchangeDeleteCallback | None = None) -> None:
    """
    Delete the exchange.

    :param exchange: The exchange name
    :param if_unused: only delete if the exchange is unused
    :param callback: callback(pika.frame.Method) for method Exchange.DeleteOk
    :returns:``None``. Method frame from the Exchange.Delete-ok response is delivered to
        ``callback`` when synchronous (no ok frame in nowait mode).
    :raises ValueError:
    """
    self._raise_if_not_open()
    nowait = validators.rpc_completion_callback(callback)
    return self._rpc(spec.Exchange.Delete(0, exchange, if_unused,
                                          nowait), callback,
                     [spec.Exchange.DeleteOk] if not nowait else [])

exchange_unbind

exchange_unbind(
    destination: str | None = None,
    source: str | None = None,
    routing_key: str = '',
    arguments: dict[str, Any] | None = None,
    callback: _OnExchangeUnbindCallback | None = None,
) -> None

Unbind an exchange from another exchange.

PARAMETER DESCRIPTION
destination

The destination exchange to unbind

TYPE: str | None DEFAULT: None

source

The source exchange to unbind from

TYPE: str | None DEFAULT: None

routing_key

The routing key to unbind

TYPE: str DEFAULT: ''

arguments

Custom key/value pair arguments for the binding

TYPE: dict[str, Any] | None DEFAULT: None

callback

callback(pika.frame.Method) for method Exchange.UnbindOk

TYPE: _OnExchangeUnbindCallback | None DEFAULT: None

RETURNS DESCRIPTION
None

None. Method frame from the Exchange.Unbind-ok response is delivered to callback when synchronous (no ok frame in nowait mode).

RAISES DESCRIPTION
ValueError
Source code in pika/channel.py
def exchange_unbind(
        self,
        destination: str | None = None,
        source: str | None = None,
        routing_key: str = '',
        arguments: dict[str, Any] | None = None,
        callback: _OnExchangeUnbindCallback | None = None) -> None:
    """
    Unbind an exchange from another exchange.

    :param destination: The destination exchange to unbind
    :param source: The source exchange to unbind from
    :param routing_key: The routing key to unbind
    :param arguments: Custom key/value pair arguments for the binding
    :param callback: callback(pika.frame.Method) for method Exchange.UnbindOk
    :returns:``None``. Method frame from the Exchange.Unbind-ok response is delivered to
        ``callback`` when synchronous (no ok frame in nowait mode).
    :raises ValueError:
    """
    self._raise_if_not_open()
    nowait = validators.rpc_completion_callback(callback)
    return self._rpc(
        spec.Exchange.Unbind(0, destination, source, routing_key, nowait,
                             arguments), callback,
        [spec.Exchange.UnbindOk] if not nowait else [])

flow

flow(
    active: bool, callback: _OnFlowCallback | None = None
) -> None

Turn Channel flow control off and on.

Pass a callback to be notified of the response from the server. active is a bool. Callback should expect a bool in response indicating channel flow state. For more information, please reference:

https://www.rabbitmq.com/amqp-0-9-1-reference.html#channel.flow

PARAMETER DESCRIPTION
active

Turn flow on or off

TYPE: bool

callback

callback(bool) upon completion

TYPE: _OnFlowCallback | None DEFAULT: None

RAISES DESCRIPTION
ValueError
Source code in pika/channel.py
def flow(self,
         active: bool,
         callback: _OnFlowCallback | None = None) -> None:
    """
    Turn Channel flow control off and on.

    Pass a callback to be notified of the response from the server. active is a bool. Callback
    should expect a bool in response indicating channel flow state. For more information, please
    reference:

    https://www.rabbitmq.com/amqp-0-9-1-reference.html#channel.flow

    :param active: Turn flow on or off
    :param callback: callback(bool) upon completion
    :raises ValueError:
    """
    self._raise_if_not_open()
    validators.rpc_completion_callback(callback)
    self._on_flowok_callback = callback
    self._rpc(spec.Channel.Flow(active), self._on_flowok,
              [spec.Channel.FlowOk])

open

open() -> None

Open the channel.

Source code in pika/channel.py
def open(self) -> None:
    """Open the channel."""
    self._set_state(self.OPENING)
    self._add_callbacks()
    self._rpc(spec.Channel.Open(), self._on_openok, [spec.Channel.OpenOk])

queue_bind

queue_bind(
    queue: str,
    exchange: str,
    routing_key: str | None = None,
    arguments: dict[str, Any] | None = None,
    callback: _OnQueueBindCallback | None = None,
) -> None

Bind the queue to the specified exchange.

PARAMETER DESCRIPTION
queue

The queue to bind to the exchange

TYPE: str

exchange

The source exchange to bind to

TYPE: str

routing_key

The routing key to bind on

TYPE: str | None DEFAULT: None

arguments

Custom key/value pair arguments for the binding

TYPE: dict[str, Any] | None DEFAULT: None

callback

callback(pika.frame.Method) for method Queue.BindOk

TYPE: _OnQueueBindCallback | None DEFAULT: None

RETURNS DESCRIPTION
None

None. Method frame from the Queue.Bind-ok response is delivered to callback when synchronous (no ok frame in nowait mode).

RAISES DESCRIPTION
ValueError
Source code in pika/channel.py
def queue_bind(self,
               queue: str,
               exchange: str,
               routing_key: str | None = None,
               arguments: dict[str, Any] | None = None,
               callback: _OnQueueBindCallback | None = None) -> None:
    """
    Bind the queue to the specified exchange.

    :param queue: The queue to bind to the exchange
    :param exchange: The source exchange to bind to
    :param routing_key: The routing key to bind on
    :param arguments: Custom key/value pair arguments for the binding
    :param callback: callback(pika.frame.Method) for method Queue.BindOk
    :returns:``None``. Method frame from the Queue.Bind-ok response is delivered to ``callback``
        when synchronous (no ok frame in nowait mode).
    :raises ValueError:
    """
    validators.require_string(queue, 'queue')
    validators.require_string(exchange, 'exchange')
    self._raise_if_not_open()
    nowait = validators.rpc_completion_callback(callback)
    if routing_key is None:
        routing_key = queue
    return self._rpc(
        spec.Queue.Bind(0, queue, exchange, routing_key, nowait,
                        arguments or {}), callback,
        [spec.Queue.BindOk] if not nowait else [])

queue_declare

queue_declare(
    queue: str,
    passive: bool = False,
    durable: bool = False,
    exclusive: bool = False,
    auto_delete: bool = False,
    arguments: dict[str, Any] | None = None,
    callback: _OnQueueDeclareCallback | None = None,
) -> None

Declare queue, create if needed.

This method creates or checks a queue. When creating a new queue the client can specify various properties that control the durability of the queue and its contents, and the level of sharing for the queue.

Use an empty string as the queue name for the broker to auto-generate one

PARAMETER DESCRIPTION
queue

The queue name; if empty string, the broker will create a unique queue name

TYPE: str

passive

Only check to see if the queue exists

TYPE: bool DEFAULT: False

durable

Survive reboots of the broker

TYPE: bool DEFAULT: False

exclusive

Only allow access by the current connection

TYPE: bool DEFAULT: False

auto_delete

Delete after consumer cancels or disconnects

TYPE: bool DEFAULT: False

arguments

Custom key/value arguments for the queue

TYPE: dict[str, Any] | None DEFAULT: None

callback

callback(pika.frame.Method) for method Queue.DeclareOk

TYPE: _OnQueueDeclareCallback | None DEFAULT: None

RETURNS DESCRIPTION
None

None. Method frame from the Queue.Declare-ok response is delivered to callback when synchronous (no ok frame in nowait mode).

RAISES DESCRIPTION
ValueError
Source code in pika/channel.py
def queue_declare(self,
                  queue: str,
                  passive: bool = False,
                  durable: bool = False,
                  exclusive: bool = False,
                  auto_delete: bool = False,
                  arguments: dict[str, Any] | None = None,
                  callback: _OnQueueDeclareCallback | None = None) -> None:
    """
    Declare queue, create if needed.

    This method creates or checks a queue. When creating a new queue the client can specify various
    properties that control the durability of the queue and its contents,
    and the level of sharing for the queue.

    Use an empty string as the queue name for the broker to auto-generate
    one

    :param queue: The queue name; if empty string, the broker will
        create a unique queue name
    :param passive: Only check to see if the queue exists
    :param durable: Survive reboots of the broker
    :param exclusive: Only allow access by the current connection
    :param auto_delete: Delete after consumer cancels or disconnects
    :param arguments: Custom key/value arguments for the queue
    :param callback: callback(pika.frame.Method) for method Queue.DeclareOk
    :returns: ``None``. Method frame from the Queue.Declare-ok response is
        delivered to ``callback`` when synchronous (no ok frame in nowait
        mode).
    :raises ValueError:
    """
    validators.require_string(queue, 'queue')
    self._raise_if_not_open()
    nowait = validators.rpc_completion_callback(callback)

    condition: Any
    if queue:
        condition = (spec.Queue.DeclareOk, {'queue': queue})
    else:
        condition = spec.Queue.DeclareOk
    replies = [condition] if not nowait else []

    return self._rpc(
        spec.Queue.Declare(0, queue, passive, durable, exclusive,
                           auto_delete, nowait, arguments or {}), callback,
        replies)

queue_delete

queue_delete(
    queue: str,
    if_unused: bool = False,
    if_empty: bool = False,
    callback: _OnQueueDeleteCallback | None = None,
) -> None

Delete a queue from the broker.

PARAMETER DESCRIPTION
queue

The queue to delete

TYPE: str

if_unused

only delete if it's unused

TYPE: bool DEFAULT: False

if_empty

only delete if the queue is empty

TYPE: bool DEFAULT: False

callback

callback(pika.frame.Method) for method Queue.DeleteOk

TYPE: _OnQueueDeleteCallback | None DEFAULT: None

RETURNS DESCRIPTION
None

None. Method frame from the Queue.Delete-ok response is delivered to callback when synchronous (no ok frame in nowait mode).

RAISES DESCRIPTION
ValueError
Source code in pika/channel.py
def queue_delete(self,
                 queue: str,
                 if_unused: bool = False,
                 if_empty: bool = False,
                 callback: _OnQueueDeleteCallback | None = None) -> None:
    """
    Delete a queue from the broker.

    :param queue: The queue to delete
    :param if_unused: only delete if it's unused
    :param if_empty: only delete if the queue is empty
    :param callback: callback(pika.frame.Method) for method Queue.DeleteOk
    :returns:``None``. Method frame from the Queue.Delete-ok response is delivered to
        ``callback`` when synchronous (no ok frame in nowait mode).
    :raises ValueError:
    """
    self._raise_if_not_open()
    validators.require_string(queue, 'queue')
    nowait = validators.rpc_completion_callback(callback)
    replies = [spec.Queue.DeleteOk] if not nowait else []
    return self._rpc(
        spec.Queue.Delete(0, queue, if_unused, if_empty, nowait), callback,
        replies)

queue_purge

queue_purge(
    queue: str,
    callback: _OnQueuePurgeCallback | None = None,
) -> None

Purge all of the messages from the specified queue.

PARAMETER DESCRIPTION
queue

The queue to purge

TYPE: str

callback

callback(pika.frame.Method) for method Queue.PurgeOk

TYPE: _OnQueuePurgeCallback | None DEFAULT: None

RETURNS DESCRIPTION
None

None. Method frame from the Queue.Purge-ok response is delivered to callback when synchronous (no ok frame in nowait mode).

RAISES DESCRIPTION
ValueError
Source code in pika/channel.py
def queue_purge(self,
                queue: str,
                callback: _OnQueuePurgeCallback | None = None) -> None:
    """
    Purge all of the messages from the specified queue.

    :param queue: The queue to purge
    :param callback: callback(pika.frame.Method) for method Queue.PurgeOk
    :returns:``None``. Method frame from the Queue.Purge-ok response is delivered to
        ``callback`` when synchronous (no ok frame in nowait mode).
    :raises ValueError:
    """
    self._raise_if_not_open()
    validators.require_string(queue, 'queue')
    nowait = validators.rpc_completion_callback(callback)
    replies = [spec.Queue.PurgeOk] if not nowait else []
    return self._rpc(spec.Queue.Purge(0, queue, nowait), callback, replies)

queue_unbind

queue_unbind(
    queue: str,
    exchange: str | None = None,
    routing_key: str | None = None,
    arguments: dict[str, Any] | None = None,
    callback: _OnQueueUnbindCallback | None = None,
) -> None

Unbind a queue from an exchange.

PARAMETER DESCRIPTION
queue

The queue to unbind from the exchange

TYPE: str

exchange

The source exchange to bind from

TYPE: str | None DEFAULT: None

routing_key

The routing key to unbind

TYPE: str | None DEFAULT: None

arguments

Custom key/value pair arguments for the binding

TYPE: dict[str, Any] | None DEFAULT: None

callback

callback(pika.frame.Method) for method Queue.UnbindOk

TYPE: _OnQueueUnbindCallback | None DEFAULT: None

RETURNS DESCRIPTION
None

None. Method frame from the Queue.Unbind-ok response is delivered to callback when provided.

RAISES DESCRIPTION
ValueError
Source code in pika/channel.py
def queue_unbind(self,
                 queue: str,
                 exchange: str | None = None,
                 routing_key: str | None = None,
                 arguments: dict[str, Any] | None = None,
                 callback: _OnQueueUnbindCallback | None = None) -> None:
    """
    Unbind a queue from an exchange.

    :param queue: The queue to unbind from the exchange
    :param exchange: The source exchange to bind from
    :param routing_key: The routing key to unbind
    :param arguments: Custom key/value pair arguments for the binding
    :param callback: callback(pika.frame.Method) for method Queue.UnbindOk
    :returns:``None``. Method frame from the Queue.Unbind-ok response is delivered to
        ``callback`` when provided.
    :raises ValueError:
    """
    self._raise_if_not_open()
    validators.require_string(queue, 'queue')
    validators.rpc_completion_callback(callback)
    if routing_key is None:
        routing_key = queue
    return self._rpc(
        spec.Queue.Unbind(0, queue, exchange, routing_key, arguments or {}),
        callback, [spec.Queue.UnbindOk])

tx_commit

tx_commit(
    callback: _OnTxCommitCallback | None = None,
) -> None

Commit a transaction.

PARAMETER DESCRIPTION
callback

callback(pika.frame.Method) for method Tx.CommitOk

TYPE: _OnTxCommitCallback | None DEFAULT: None

RETURNS DESCRIPTION
None

None. Method frame from the Tx.Commit-ok response is delivered to callback when provided.

RAISES DESCRIPTION
ValueError
Source code in pika/channel.py
def tx_commit(self, callback: _OnTxCommitCallback | None = None) -> None:
    """
    Commit a transaction.

    :param callback: callback(pika.frame.Method) for method Tx.CommitOk
    :returns:``None``. Method frame from the Tx.Commit-ok response is delivered to ``callback``
        when provided.
    :raises ValueError:
    """
    self._raise_if_not_open()
    validators.rpc_completion_callback(callback)
    return self._rpc(spec.Tx.Commit(), callback, [spec.Tx.CommitOk])

tx_rollback

tx_rollback(
    callback: _OnTxRollbackCallback | None = None,
) -> None

Rollback a transaction.

PARAMETER DESCRIPTION
callback

callback(pika.frame.Method) for method Tx.RollbackOk

TYPE: _OnTxRollbackCallback | None DEFAULT: None

RETURNS DESCRIPTION
None

None. Method frame from the Tx.Rollback-ok response is delivered to callback when provided.

RAISES DESCRIPTION
ValueError
Source code in pika/channel.py
def tx_rollback(self,
                callback: _OnTxRollbackCallback | None = None) -> None:
    """
    Rollback a transaction.

    :param callback: callback(pika.frame.Method) for method Tx.RollbackOk
    :returns:``None``. Method frame from the Tx.Rollback-ok response is delivered to
        ``callback`` when provided.
    :raises ValueError:
    """
    self._raise_if_not_open()
    validators.rpc_completion_callback(callback)
    return self._rpc(spec.Tx.Rollback(), callback, [spec.Tx.RollbackOk])

tx_select

tx_select(
    callback: _OnTxSelectCallback | None = None,
) -> None

Select standard transaction mode.

This method sets the channel to use standard transactions. The client must use this method at least once on a channel before using the Commit or Rollback methods.

PARAMETER DESCRIPTION
callback

callback(pika.frame.Method) for method Tx.SelectOk

TYPE: _OnTxSelectCallback | None DEFAULT: None

RETURNS DESCRIPTION
None

None. Method frame from the Tx.Select-ok response is delivered to callback when provided.

RAISES DESCRIPTION
ValueError
Source code in pika/channel.py
def tx_select(self, callback: _OnTxSelectCallback | None = None) -> None:
    """
    Select standard transaction mode.

    This method sets the channel to use standard transactions. The client must use this method
    at least once on a channel before using the Commit or Rollback methods.

    :param callback: callback(pika.frame.Method) for method Tx.SelectOk
    :returns:``None``. Method frame from the Tx.Select-ok response is delivered to ``callback``
        when provided.
    :raises ValueError:
    """
    self._raise_if_not_open()
    validators.rpc_completion_callback(callback)
    return self._rpc(spec.Tx.Select(), callback, [spec.Tx.SelectOk])

_add_callbacks

_add_callbacks() -> None

Callbacks that add the required behavior for a channel when connecting and connected to a server.

Source code in pika/channel.py
def _add_callbacks(self) -> None:
    """Callbacks that add the required behavior for a channel when connecting and connected to a
    server.
    """
    # Add a callback for Basic.GetEmpty
    self.callbacks.add(self.channel_number, spec.Basic.GetEmpty,
                       self._on_getempty, False)

    # Add a callback for Basic.Cancel
    self.callbacks.add(self.channel_number, spec.Basic.Cancel,
                       self._on_cancel, False)

    # Deprecated in newer versions of RabbitMQ but still register for it
    self.callbacks.add(self.channel_number, spec.Channel.Flow,
                       self._on_flow, False)

    # Add a callback for when the server closes our channel
    self.callbacks.add(self.channel_number, spec.Channel.Close,
                       self._on_close_from_broker, True)

_add_on_cleanup_callback

_add_on_cleanup_callback(
    callback: Callable[..., Any],
) -> None

For internal use only (e.g., Connection needs to remove closed channels from its channel container). Pass a callback function that will be called when the channel is being cleaned up after all channel-close callbacks callbacks.

PARAMETER DESCRIPTION
callback

The callback to call, having the signature: callback(channel)

TYPE: Callable[..., Any]

Source code in pika/channel.py
def _add_on_cleanup_callback(self, callback: Callable[..., Any]) -> None:
    """
    For internal use only (e.g., Connection needs to remove closed channels from its channel
    container). Pass a callback function that will be called when the channel is being cleaned
    up after all channel-close callbacks callbacks.

    :param callback: The callback to call, having the
        signature: callback(channel)
    """
    self.callbacks.add(self.channel_number,
                       self._ON_CHANNEL_CLEANUP_CB_KEY,
                       callback,
                       one_shot=True,
                       only_caller=self)

_cleanup

_cleanup() -> None

Remove all consumers and any callbacks for the channel.

Source code in pika/channel.py
def _cleanup(self) -> None:
    """Remove all consumers and any callbacks for the channel."""
    self.callbacks.process(self.channel_number,
                           self._ON_CHANNEL_CLEANUP_CB_KEY, self, self)
    self._consumers = {}
    self._cancelled = set()
    self._nowait_cancelled = deque()
    self._consumers_with_noack = set()
    self.callbacks.cleanup(str(self.channel_number))
    self._cookie = None

_cleanup_consumer_ref

_cleanup_consumer_ref(consumer_tag: str) -> None

Remove any references to the consumer tag in internal structures for consumer state.

PARAMETER DESCRIPTION
consumer_tag

The consumer tag to cleanup

TYPE: str

Source code in pika/channel.py
def _cleanup_consumer_ref(self, consumer_tag: str) -> None:
    """
    Remove any references to the consumer tag in internal structures for consumer state.

    :param consumer_tag: The consumer tag to cleanup
    """
    self._consumers_with_noack.discard(consumer_tag)
    self._consumers.pop(consumer_tag, None)
    self._cancelled.discard(consumer_tag)

_retain_cancelled_tag

_retain_cancelled_tag(consumer_tag: str) -> None

Retain a nowait-cancelled consumer tag, evicting the oldest once the cap is reached.

A cancelled tag stays in _cancelled (and _consumers_with_noack) so that a delivery the broker had already dispatched when Basic.Cancel was sent is rejected rather than left unacknowledged; see _on_deliver. A cancel that expects a Basic.CancelOk retires its own entry in _on_cancelok, but a nowait cancel asks the broker for no reply, so nothing retires it and the entries would otherwise accumulate for the life of the channel.

Bound them here instead. The number of deliveries that can still be in flight for a cancelled consumer is bounded by what the broker had already dispatched, so a cap on retained nowait-cancelled tags approximates that window: evicting in cancellation order past _MAX_RETAINED_CANCELLED_TAGS keeps retention constant in the number of cancels. The cap is not the true window, though, since it is measured in cancels rather than deliveries, so once a tag is evicted its reject-and-reserve behaviour lapses: a straggling delivery for it is logged as unexpected and left unacknowledged (see _on_deliver), and basic_consume will accept the tag again. The default is large enough that this only occurs under extreme nowait-cancel churn.

A tag cannot be queued twice: basic_consume refuses a tag that is still in _cancelled, and on the nowait path only eviction takes it back out again.

PARAMETER DESCRIPTION
consumer_tag

The consumer tag just cancelled with nowait

TYPE: str

Source code in pika/channel.py
def _retain_cancelled_tag(self, consumer_tag: str) -> None:
    """
    Retain a nowait-cancelled consumer tag, evicting the oldest once the cap is reached.

    A cancelled tag stays in `_cancelled` (and `_consumers_with_noack`) so that a delivery the
    broker had already dispatched when `Basic.Cancel` was sent is rejected rather than left
    unacknowledged; see `_on_deliver`.  A cancel that expects a `Basic.CancelOk` retires its own
    entry in `_on_cancelok`, but a nowait cancel asks the broker for no reply, so nothing
    retires it and the entries would otherwise accumulate for the life of the channel.

    Bound them here instead.  The number of deliveries that can still be in flight for a
    cancelled consumer is bounded by what the broker had already dispatched, so a cap on
    retained nowait-cancelled tags approximates that window: evicting in cancellation order past
    `_MAX_RETAINED_CANCELLED_TAGS` keeps retention constant in the number of cancels.  The cap
    is not the true window, though, since it is measured in cancels rather than deliveries, so
    once a tag is evicted its reject-and-reserve behaviour lapses: a straggling delivery for it
    is logged as unexpected and left unacknowledged (see `_on_deliver`), and `basic_consume`
    will accept the tag again.  The default is large enough that this only occurs under extreme
    nowait-cancel churn.

    A tag cannot be queued twice: `basic_consume` refuses a tag that is still in `_cancelled`,
    and on the nowait path only eviction takes it back out again.

    :param consumer_tag: The consumer tag just cancelled with nowait
    """
    self._nowait_cancelled.append(consumer_tag)
    while len(self._nowait_cancelled) > self._MAX_RETAINED_CANCELLED_TAGS:
        self._cleanup_consumer_ref(self._nowait_cancelled.popleft())
_get_cookie() -> Any

Used by the wrapper implementation (e.g., BlockingChannel) to retrieve the cookie that it set via _set_cookie

RETURNS DESCRIPTION
Any

opaque cookie value that was set via _set_cookie

Source code in pika/channel.py
def _get_cookie(self) -> Any:
    """
    Used by the wrapper implementation (e.g., `BlockingChannel`) to retrieve the cookie that it
    set via `_set_cookie`

    :returns: opaque cookie value that was set via `_set_cookie`
    """
    return self._cookie

_handle_content_frame

_handle_content_frame(frame_value: Frame) -> None

This is invoked by the connection when frames that are not registered with the CallbackManager have been found. This should only be the case when the frames are related to content delivery.

The _content_assembler will be invoked which will return the fully formed message in three parts when all of the body frames have been received.

PARAMETER DESCRIPTION
frame_value

The frame to deliver

TYPE: Frame

Source code in pika/channel.py
def _handle_content_frame(self, frame_value: frame.Frame) -> None:
    """
    This is invoked by the connection when frames that are not registered with the
    CallbackManager have been found. This should only be the case when the frames are related to
    content delivery.

    The _content_assembler will be invoked which will return the fully formed message in three
    parts when all of the body frames have been received.

    :param frame_value: The frame to deliver
    """
    try:
        response = self._content_assembler.process(frame_value)
    except exceptions.UnexpectedFrameError:
        self._on_unexpected_frame(frame_value)
        return

    if response:
        method_index = response[0].method.INDEX
        if method_index == spec.Basic.Deliver.INDEX:
            self._on_deliver(*response)
        elif method_index == spec.Basic.GetOk.INDEX:
            self._on_getok(*response)
        elif method_index == spec.Basic.Return.INDEX:
            self._on_return(*response)

_on_cancel

_on_cancel(method_frame: Method) -> None

When the broker cancels a consumer, delete it from our internal dictionary.

Reply with Basic.CancelOk if the broker advertises the accept_consumer_cancel_ok capability.

PARAMETER DESCRIPTION
method_frame

The method frame received

TYPE: Method

Source code in pika/channel.py
def _on_cancel(self, method_frame: frame.Method) -> None:
    """
    When the broker cancels a consumer, delete it from our internal dictionary.

    Reply with `Basic.CancelOk` if the broker advertises the `accept_consumer_cancel_ok`
    capability.

    :param method_frame: The method frame received
    """
    consumer_tag = method_frame.method.consumer_tag
    # Sent before the `_cancelled` check below, so a user-initiated cancel
    # racing a broker-sent one still gets a reply. That is safe in both
    # orders, which is not obvious from here. A broker advertising the
    # capability answers a `Basic.CancelOk` for a tag it is not waiting on
    # with `{noreply, State}`, so a late or duplicate reply is ignored
    # rather than treated as a protocol error. And if this reply reaches the
    # broker first, it releases the consumer without replying, leaving the
    # user's in-flight `Basic.Cancel` to arrive for a tag the broker no
    # longer tracks - which `cancel_consumer` answers with a `Basic.CancelOk`
    # anyway ("Spec requires we ignore this situation"), so the pending RPC
    # still completes instead of hanging.
    if self.is_open and self.connection.accept_consumer_cancel_ok:
        self._send_method(spec.Basic.CancelOk(consumer_tag=consumer_tag))

    if consumer_tag in self._cancelled:
        # User-initiated cancel is waiting for Cancel-ok
        return

    self._cleanup_consumer_ref(consumer_tag)

_on_cancelok

_on_cancelok(method_frame: Method) -> None

Called in response to a frame from the Broker when the client sends Basic.Cancel.

PARAMETER DESCRIPTION
method_frame

The method frame received

TYPE: Method

Source code in pika/channel.py
def _on_cancelok(self, method_frame: frame.Method) -> None:
    """
    Called in response to a frame from the Broker when the client sends Basic.Cancel.

    :param method_frame: The method frame received
    """
    self._cleanup_consumer_ref(method_frame.method.consumer_tag)

_transition_to_closed

_transition_to_closed() -> None

Common logic for transitioning the channel to the CLOSED state:

Set state to CLOSED, dispatch callbacks registered via Channel.add_on_close_callback(), and mop up.

Assumes that the channel is not in CLOSED state and that self._closing_reason has been set up

Source code in pika/channel.py
def _transition_to_closed(self) -> None:
    """Common logic for transitioning the channel to the CLOSED state:

    Set state to CLOSED, dispatch callbacks registered via
    `Channel.add_on_close_callback()`, and mop up.

    Assumes that the channel is not in CLOSED state and that
    `self._closing_reason` has been set up

    """
    assert not self.is_closed
    assert self._closing_reason is not None

    self._set_state(self.CLOSED)

    try:
        self.callbacks.process(self.channel_number, '_on_channel_close',
                               self, self, self._closing_reason)
    finally:
        self._cleanup()

_on_close_from_broker

_on_close_from_broker(method_frame: Method) -> None

Handle Channel.Close from broker.

PARAMETER DESCRIPTION
method_frame

Method frame with Channel.Close method

TYPE: Method

Source code in pika/channel.py
def _on_close_from_broker(self, method_frame: frame.Method) -> None:
    """
    Handle `Channel.Close` from broker.

    :param method_frame: Method frame with Channel.Close method
    """
    LOGGER.warning('Received remote Channel.Close (%s): %r on %s',
                   method_frame.method.reply_code,
                   method_frame.method.reply_text, self)
    # Note, we should not be called when channel is already closed
    assert not self.is_closed

    # AMQP 0.9.1 requires CloseOk response to Channel.Close;
    self._send_method(spec.Channel.CloseOk())

    # Save the details, possibly overriding user-provided values if
    # user-initiated close is pending (in which case they will be provided
    # to user callback when CloseOk arrives).
    self._closing_reason = exceptions.ChannelClosedByBroker(
        method_frame.method.reply_code, method_frame.method.reply_text)

    if self.is_closing:
        # Since we may have already put Channel.Close on the wire, we need
        # to wait for CloseOk before cleaning up to avoid a race condition
        # whereby our channel number might get reused before our CloseOk
        # arrives
        #
        # NOTE: if our Channel.Close destined for the broker was blocked by
        # an earlier synchronous method, this call will drop it and perform
        # a meta-close (see `_on_close_meta()` which fakes receipt of
        # `Channel.CloseOk` and dispatches the `'_on_channel_close'`
        # callbacks.
        self._drain_blocked_methods_on_remote_close()
    else:
        self._transition_to_closed()

_on_close_meta

_on_close_meta(reason: Exception | None) -> None

Handle meta-close request from either a remote Channel.Close from the broker (when a pending Channel.Close method is queued for execution) or a Connection's cleanup logic after sudden connection loss. We use this opportunity to transition to CLOSED state, clean up the channel, and dispatch the on-channel-closed callbacks.

PARAMETER DESCRIPTION
reason

Exception describing the reason for closing.

TYPE: Exception | None

Source code in pika/channel.py
def _on_close_meta(self, reason: Exception | None) -> None:
    """
    Handle meta-close request from either a remote Channel.Close from the broker (when a pending
    Channel.Close method is queued for execution) or a Connection's cleanup logic after sudden
    connection loss. We use this opportunity to transition to CLOSED state, clean up the
    channel, and dispatch the on-channel-closed callbacks.

    :param reason: Exception describing the reason for closing.
    """
    LOGGER.debug('Handling meta-close on %s: %r', self, reason)

    if not self.is_closed:
        self._closing_reason = reason
        self._transition_to_closed()

_on_closeok

_on_closeok(method_frame: Method) -> None

Invoked when RabbitMQ replies to a Channel.Close method.

PARAMETER DESCRIPTION
method_frame

Method frame with Channel.CloseOk method

TYPE: Method

Source code in pika/channel.py
def _on_closeok(self, method_frame: frame.Method) -> None:
    """
    Invoked when RabbitMQ replies to a Channel.Close method.

    :param method_frame: Method frame with Channel.CloseOk method
    """
    LOGGER.info('Received %s on %s', method_frame.method, self)

    self._transition_to_closed()

_on_deliver

_on_deliver(
    method_frame: Method, header_frame: Header, body: bytes
) -> None

Cope with reentrancy.

If a particular consumer is still active when another delivery appears for it, queue the deliveries up until it finally exits.

PARAMETER DESCRIPTION
method_frame

The method frame received

TYPE: Method

header_frame

The header frame received

TYPE: Header

body

The body received

TYPE: bytes

Source code in pika/channel.py
def _on_deliver(self, method_frame: frame.Method,
                header_frame: frame.Header, body: bytes) -> None:
    """
    Cope with reentrancy.

    If a particular consumer is still active when another delivery appears for it, queue the
    deliveries up until it finally exits.

    :param method_frame: The method frame received
    :param header_frame: The header frame received
    :param body: The body received
    """
    consumer_tag = method_frame.method.consumer_tag

    if consumer_tag in self._cancelled:
        if self.is_open and consumer_tag not in self._consumers_with_noack:
            self.basic_reject(method_frame.method.delivery_tag)
        return

    if consumer_tag not in self._consumers:
        LOGGER.error('Unexpected delivery: %r', method_frame)
        return

    self._consumers[consumer_tag](self, method_frame.method,
                                  header_frame.properties, body)

_on_eventok

_on_eventok(method_frame: Method) -> None

Generic events that returned ok that may have internal callbacks.

We keep a list of what we've yet to implement so that we don't silently drain events that we don't support.

PARAMETER DESCRIPTION
method_frame

The method frame received

TYPE: Method

Source code in pika/channel.py
def _on_eventok(self, method_frame: frame.Method) -> None:
    """
    Generic events that returned ok that may have internal callbacks.

    We keep a list of what we've yet to implement so that we don't silently drain events that we
    don't support.

    :param method_frame: The method frame received
    """
    LOGGER.debug('Discarding frame %r', method_frame)

_on_flow

_on_flow(_method_frame_unused: Method) -> None

Called if the server sends a Channel.Flow frame.

PARAMETER DESCRIPTION
_method_frame_unused

The Channel.Flow frame

TYPE: Method

Source code in pika/channel.py
def _on_flow(self, _method_frame_unused: frame.Method) -> None:
    """
    Called if the server sends a Channel.Flow frame.

    :param _method_frame_unused: The Channel.Flow frame
    """
    if self._has_on_flow_callback is False:
        LOGGER.warning('Channel.Flow received from server')

_on_flowok

_on_flowok(method_frame: Method) -> None

Called in response to us asking the server to toggle on Channel.Flow.

PARAMETER DESCRIPTION
method_frame

The method frame received

TYPE: Method

Source code in pika/channel.py
def _on_flowok(self, method_frame: frame.Method) -> None:
    """
    Called in response to us asking the server to toggle on Channel.Flow.

    :param method_frame: The method frame received
    """
    self.flow_active = method_frame.method.active
    if self._on_flowok_callback:
        self._on_flowok_callback(method_frame.method.active)
        self._on_flowok_callback = None
    else:
        LOGGER.warning('Channel.FlowOk received with no active callbacks')

_on_getempty

_on_getempty(method_frame: Method) -> None

When we receive an empty reply do nothing but log it.

PARAMETER DESCRIPTION
method_frame

The method frame received

TYPE: Method

Source code in pika/channel.py
def _on_getempty(self, method_frame: frame.Method) -> None:
    """
    When we receive an empty reply do nothing but log it.

    :param method_frame: The method frame received
    """
    LOGGER.debug('Received Basic.GetEmpty: %r', method_frame)
    if self._on_getok_callback is not None:
        self._on_getok_callback = None

_on_getok

_on_getok(
    method_frame: Method, header_frame: Header, body: bytes
) -> None

Called in reply to a Basic.Get when there is a message.

PARAMETER DESCRIPTION
method_frame

The method frame received

TYPE: Method

header_frame

The header frame received

TYPE: Header

body

The body received

TYPE: bytes

Source code in pika/channel.py
def _on_getok(self, method_frame: frame.Method, header_frame: frame.Header,
              body: bytes) -> None:
    """
    Called in reply to a Basic.Get when there is a message.

    :param method_frame: The method frame received
    :param header_frame: The header frame received
    :param body: The body received
    """
    if self._on_getok_callback is not None:
        callback = self._on_getok_callback
        self._on_getok_callback = None
        callback(self, method_frame.method, header_frame.properties, body)
    else:
        LOGGER.error('Basic.GetOk received with no active callback')

_on_openok

_on_openok(method_frame: Method) -> None

Called by our callback handler when we receive a Channel.OpenOk and subsequently calls our _on_openok_callback which was passed into the Channel constructor. The reason we do this is because we want to make sure that the on_open_callback parameter passed into the Channel constructor is not the first callback we make.

Suppress the state transition and callback if channel is already in CLOSING state.

PARAMETER DESCRIPTION
method_frame

Channel.OpenOk frame

TYPE: Method

Source code in pika/channel.py
def _on_openok(self, method_frame: frame.Method) -> None:
    """
    Called by our callback handler when we receive a Channel.OpenOk and subsequently calls our
    _on_openok_callback which was passed into the Channel constructor. The reason we do this is
    because we want to make sure that the on_open_callback parameter passed into the Channel
    constructor is not the first callback we make.

    Suppress the state transition and callback if channel is already in CLOSING state.

    :param method_frame: Channel.OpenOk frame
    """
    # Suppress OpenOk if the user or Connection.Close started closing it
    # before open completed.
    if self.is_closing:
        LOGGER.debug('Suppressing while in closing state: %s', method_frame)
    else:
        self._set_state(self.OPEN)
        if self._on_openok_callback is not None:
            self._on_openok_callback(self)

_on_return

_on_return(
    method_frame: Method, header_frame: Header, body: bytes
) -> None

Called if the server sends a Basic.Return frame.

PARAMETER DESCRIPTION
method_frame

The Basic.Return frame

TYPE: Method

header_frame

The content header frame

TYPE: Header

body

The message body

TYPE: bytes

Source code in pika/channel.py
def _on_return(self, method_frame: frame.Method, header_frame: frame.Header,
               body: bytes) -> None:
    """
    Called if the server sends a Basic.Return frame.

    :param method_frame: The Basic.Return frame
    :param header_frame: The content header frame
    :param body: The message body
    """
    if not self.callbacks.process(self.channel_number, '_on_return', self,
                                  self, method_frame.method,
                                  header_frame.properties, body):
        LOGGER.debug('Basic.Return received from server (%r, %r)',
                     method_frame.method, header_frame.properties)

_on_selectok

_on_selectok(method_frame: Method) -> None

Called when the broker sends a Confirm.SelectOk frame.

PARAMETER DESCRIPTION
method_frame

The method frame received

TYPE: Method

Source code in pika/channel.py
def _on_selectok(self, method_frame: frame.Method) -> None:
    """
    Called when the broker sends a Confirm.SelectOk frame.

    :param method_frame: The method frame received
    """
    LOGGER.debug('Confirm.SelectOk Received: %r', method_frame)

_on_synchronous_complete

_on_synchronous_complete(
    _method_frame_unused: Method,
) -> None

This is called when a synchronous command is completed.

It will undo the blocking state and send all the frames that stacked up while we were in the blocking state.

PARAMETER DESCRIPTION
_method_frame_unused

The method frame received

TYPE: Method

Source code in pika/channel.py
def _on_synchronous_complete(self,
                             _method_frame_unused: frame.Method) -> None:
    """
    This is called when a synchronous command is completed.

    It will undo the blocking state and send all the frames that stacked up while we were in the
    blocking state.

    :param _method_frame_unused: The method frame received
    """
    LOGGER.debug('%i blocked frames', len(self._blocked))
    self._blocking = None
    # self._blocking must be checked here as a callback could
    # potentially change the state of that variable during an
    # iteration of the while loop
    while self._blocked and self._blocking is None:
        self._rpc(*self._blocked.popleft())

_drain_blocked_methods_on_remote_close

_drain_blocked_methods_on_remote_close() -> None

This is called when the broker sends a Channel.Close while the client is in CLOSING state. This method checks the blocked method queue for a pending client-initiated Channel.Close method and ensures its callbacks are processed, but does not send the method to the broker.

The broker may close the channel before responding to outstanding in-transit synchronous methods, or even before these methods have been sent to the broker. AMQP 0.9.1 obliges the server to drop all methods arriving on a closed channel other than Channel.CloseOk and Channel.Close. Since the response to a synchronous method that blocked the channel never arrives, the channel never becomes unblocked, and the Channel.Close, if any, in the blocked queue has no opportunity to be sent, and thus its completion callback would never be called.

Source code in pika/channel.py
def _drain_blocked_methods_on_remote_close(self) -> None:
    """
    This is called when the broker sends a Channel.Close while the client is in CLOSING state.
    This method checks the blocked method queue for a pending client-initiated Channel.Close
    method and ensures its callbacks are processed, but does not send the method to the broker.

    The broker may close the channel before responding to outstanding in-transit synchronous
    methods, or even before these methods have been sent to the broker. AMQP 0.9.1 obliges the
    server to drop all methods arriving on a closed channel other than Channel.CloseOk and
    Channel.Close. Since the response to a synchronous method that blocked the channel never
    arrives, the channel never becomes unblocked, and the Channel.Close, if any, in the blocked
    queue has no opportunity to be sent, and thus its completion callback would never be called.
    """
    LOGGER.debug(
        'Draining %i blocked frames due to broker-requested Channel.Close',
        len(self._blocked))
    while self._blocked:
        method = self._blocked.popleft()[0]
        if isinstance(method, spec.Channel.Close):
            # The desired reason is already in self._closing_reason
            self._on_close_meta(self._closing_reason)
        else:
            LOGGER.debug('Ignoring drained blocked method: %s', method)

_rpc

_rpc(
    method: Method,
    callback: Callable[..., Any] | None = None,
    acceptable_replies: Sequence[
        type[Method] | tuple[type[Method], dict[str, Any]]
    ]
    | None = None,
) -> None

Make a synchronous channel RPC call for a synchronous method frame.

If the channel is already in the blocking state, then enqueue the request, but don't send it at this time; it will be eventually sent by _on_synchronous_complete after the prior blocking request receives a response. If the channel is not in the blocking state and acceptable_replies is not empty, transition the channel to the blocking state and register for _on_synchronous_complete before sending the request.

NOTE: A callback must be accompanied by non-empty acceptable_replies.

PARAMETER DESCRIPTION
method

The AMQP method to invoke

TYPE: Method

callback

The callback for the RPC response

TYPE: Callable[..., Any] | None DEFAULT: None

acceptable_replies

A (possibly empty) sequence of replies this RPC call expects or None

TYPE: Sequence[type[Method] | tuple[type[Method], dict[str, Any]]] | None DEFAULT: None

Source code in pika/channel.py
def _rpc(
    self,
    method: amqp_object.Method,
    callback: Callable[..., Any] | None = None,
    acceptable_replies: Sequence[type[amqp_object.Method] |
                                 tuple[type[amqp_object.Method],
                                       dict[str, Any]]] | None = None
) -> None:
    """
    Make a synchronous channel RPC call for a synchronous method frame.

    If the channel is already in the blocking state, then enqueue the request,
    but don't send it at this time; it will be eventually sent by
    `_on_synchronous_complete` after the prior blocking request receives a
    response. If the channel is not in the blocking state and
    `acceptable_replies` is not empty, transition the channel to the
    blocking state and register for `_on_synchronous_complete` before
    sending the request.

    NOTE: A callback must be accompanied by non-empty acceptable_replies.

    :param method: The AMQP method to invoke
    :param callback: The callback for the RPC response
    :param acceptable_replies: A (possibly empty) sequence of
        replies this RPC call expects or None
    """
    assert method.synchronous, (
        f'Only synchronous-capable methods may be used with _rpc: {method!r}'
    )

    # Validate we got None or a list of acceptable_replies
    if not isinstance(acceptable_replies, (type(None), list)):
        raise TypeError('acceptable_replies should be list or None')

    if callback is not None:
        # Validate the callback is callable
        if not callable(callback):
            raise TypeError('callback should be None or a callable')

        # Make sure that callback is accompanied by acceptable replies
        if not acceptable_replies:
            raise ValueError(
                'Unexpected callback for asynchronous (nowait) operation.')

    # Make sure the channel is not closed yet
    if self.is_closed:
        self._raise_if_not_open()

    # If the channel is blocking, add subsequent commands to our stack
    if self._blocking:
        LOGGER.debug(
            'Already in blocking state, so enqueueing method %s; '
            'acceptable_replies=%r', method, acceptable_replies)
        self._blocked.append([method, callback, acceptable_replies])
        return

    # Note: _send_method can throw exceptions if there are framing errors
    # or invalid data passed in. Call it here to prevent self._blocking
    # from being set if an exception is thrown. This also prevents
    # acceptable_replies registering callbacks when exceptions are thrown
    self._send_method(method)

    # If acceptable replies are set, add callbacks
    if acceptable_replies:
        # Block until a response frame is received for synchronous frames
        self._blocking = method.NAME
        LOGGER.debug(
            'Entering blocking state on frame %s; acceptable_replies=%r',
            method, acceptable_replies)

        for reply in acceptable_replies:
            if isinstance(reply, tuple):
                reply, arguments = reply
            else:
                arguments = None
            LOGGER.debug('Adding on_synchronous_complete callback')
            self.callbacks.add(self.channel_number,
                               reply,
                               self._on_synchronous_complete,
                               arguments=arguments)
            if callback is not None:
                LOGGER.debug('Adding passed-in RPC response callback')
                self.callbacks.add(self.channel_number,
                                   reply,
                                   callback,
                                   arguments=arguments)

_raise_if_not_open

_raise_if_not_open() -> None

If channel is not in the OPEN state, raises ChannelWrongStateError with reply_code and reply_text corresponding to current state.

RAISES DESCRIPTION
exceptions.ChannelWrongStateError

if channel is not in OPEN state.

Source code in pika/channel.py
def _raise_if_not_open(self) -> None:
    """
    If channel is not in the OPEN state, raises ChannelWrongStateError with `reply_code` and
    `reply_text` corresponding to current state.

    :raises exceptions.ChannelWrongStateError: if channel is not in OPEN state.
    """
    if self._state == self.OPEN:
        return

    if self._state == self.OPENING:
        raise exceptions.ChannelWrongStateError(
            'Channel is opening, but is not usable yet.')

    if self._state == self.CLOSING:
        raise exceptions.ChannelWrongStateError('Channel is closing.')

    # Assumed self.CLOSED
    assert self._state == self.CLOSED
    raise exceptions.ChannelWrongStateError('Channel is closed.')

_send_method

_send_method(
    method: Method,
    content: tuple[BasicProperties, bytes] | None = None,
) -> None

Shortcut wrapper to send a method through our connection, passing in the channel number.

PARAMETER DESCRIPTION
method

The method to send

TYPE: Method

content

If set, is a content frame, is tuple of properties and body.

TYPE: tuple[BasicProperties, bytes] | None DEFAULT: None

Source code in pika/channel.py
def _send_method(
        self,
        method: amqp_object.Method,
        content: tuple[spec.BasicProperties, bytes] | None = None) -> None:
    """
    Shortcut wrapper to send a method through our connection, passing in the channel number.

    :param method: The method to send
    :param content: If set, is a content frame, is tuple of properties and body.
    """
    self.connection._send_method(self.channel_number, method, content)
_set_cookie(cookie: object) -> None

Used by wrapper layer (e.g., BlockingConnection) to link the channel implementation back to the proxy. See _get_cookie.

PARAMETER DESCRIPTION
cookie

an opaque value; typically a proxy channel implementation instance (e.g., BlockingChannel instance)

TYPE: object

Source code in pika/channel.py
def _set_cookie(self, cookie: object) -> None:
    """
    Used by wrapper layer (e.g., `BlockingConnection`) to link the channel implementation back
    to the proxy. See `_get_cookie`.

    :param cookie: an opaque value; typically a proxy channel implementation instance (e.g.,
        `BlockingChannel` instance)
    """
    self._cookie = cookie

_set_state

_set_state(connection_state: int) -> None

Set the channel connection state to the specified state value.

PARAMETER DESCRIPTION
connection_state

The connection_state value

TYPE: int

Source code in pika/channel.py
def _set_state(self, connection_state: int) -> None:
    """
    Set the channel connection state to the specified state value.

    :param connection_state: The connection_state value
    """
    self._state = connection_state

_on_unexpected_frame

_on_unexpected_frame(frame_value: Frame) -> None

Invoked when a frame is received that is not setup to be processed.

PARAMETER DESCRIPTION
frame_value

The frame received

TYPE: Frame

Source code in pika/channel.py
def _on_unexpected_frame(self, frame_value: frame.Frame) -> None:
    """
    Invoked when a frame is received that is not setup to be processed.

    :param frame_value: The frame received
    """
    LOGGER.error('Unexpected frame: %r', frame_value)