# azure.servicebus.aio package

## Submodules

## azure.servicebus.aio.async_base_handler module

class `azure.servicebus.aio.async_base_handler.``BaseHandler`(endpoint, auth_config, *, loop=None, connection=None, encoding='UTF-8', debug=False, **kwargs)

  Bases: `object`

  `close`(exception=None)

    Close down the handler connection.

    If the handler has already closed, this operation will do nothing. An optional exception can be passed in to indicate that the handler was shutdown due to error. It is recommended to open a handler within a context manager as opposed to calling the method directly.

    Note

    This operation is not thread-safe.

    Parameters: | exception (Exception) – An optional exception if the handler is closing due to an error.

    Example

    Explicitly open and close a Sender.

        from azure.servicebus.aio import Message

        sender = queue_client.get_sender()
        try:
            await sender.open()
            await sender.send(Message("foobar"))
        finally:
            await sender.close()

  `open`()

    Open handler connection and authenticate session.

    If the handler is already open, this operation will do nothing. A handler opened with this method must be explicitly closed. It is recommended to open a handler within a context manager as opposed to calling the method directly.

    Note

    This operation is not thread-safe.

    Example

    Explicitly open and close a Sender.

        from azure.servicebus.aio import Message

        sender = queue_client.get_sender()
        try:
            await sender.open()
            await sender.send(Message("foobar"))
        finally:
            await sender.close()

  `reconnect`()

    Reconnect the handler.

    If the handler was disconnected from the service with a retryable error - attempt to reconnect. This method will be called automatically for most retryable errors.

## azure.servicebus.aio.async_client module

class `azure.servicebus.aio.async_client.``BaseClient`(address, name, *, shared_access_key_name=None, shared_access_key_value=None, loop=None, debug=False, **kwargs)

  Bases: `azure.servicebus.common.mixins.BaseClient`

class `azure.servicebus.aio.async_client.``QueueClient`(address, name, *, shared_access_key_name=None, shared_access_key_value=None, loop=None, debug=False, **kwargs)

  Bases: `azure.servicebus.aio.async_client.SendClientMixin`, `azure.servicebus.aio.async_client.ReceiveClientMixin`, `azure.servicebus.aio.async_client.BaseClient`

  A queue client.

  The QueueClient class defines a high level interface for sending messages to and receiving messages from an Azure Service Bus queue. If you do not wish to perform management operations, a QueueClient can be instantiated directly to perform send and receive operations to a Queue. However if a QueueClient is created directly, a get_properties operation will need to be completed in order to retrieve the properties of this queue (for example, whether it is sessionful).

  Parameters:

  - address (str) – The full URI of the Service Bus namespace. This can optionally include URL-encoded access name and key.
  - name (str) – The name of the queue to which the Client will connect.
  - shared_access_key_name (str) – The name of the shared access policy. This must be supplied if not encoded into the address.
  - shared_access_key_value (str) – The shared access key. This must be supplied if not encoded into the address.
  - loop (EventLoop) – An async event loop
  - debug (bool) – Whether to output network trace logs to the logger. Default is False.

  Example

  Create a QueueClient.

      import os
      from azure.servicebus.aio import QueueClient

      connection_str = os.environ['SERVICE_BUS_CONNECTION_STR']
      queue_client = QueueClient.from_connection_string(connection_str, name="MyQueue")
      queue_properties = queue_client.get_properties()

class `azure.servicebus.aio.async_client.``ReceiveClientMixin`

  Bases: `object`

  `get_deadletter_receiver`(transfer_deadletter=False, prefetch=0, mode=<ReceiveSettleMode.PeekLock: <ReceiverSettleMode.PeekLock: 1>>, idle_timeout=0, **kwargs)

    Get a Receiver for the deadletter endpoint of the entity.

    A Receiver represents a single open connection with which multiple receive operations can be made.

    Parameters:

    - transfer_deadletter (bool) – Whether to connect to the transfer deadletter queue, or the standard deadletter queue. Default is False, using the standard deadletter endpoint.
    - prefetch (int) – The maximum number of messages to cache with each request to the service. The default value is 0, meaning messages will be received from the service and processed one at a time. Increasing this value will improve message throughput performance but increase the change that messages will expire while they are cached if they’re not processed fast enough.
    - mode (ReceiveSettleMode) – The mode with which messages will be retrieved from the entity. The two options are PeekLock and ReceiveAndDelete. Messages received with PeekLock must be settled within a given lock period before they will be removed from the queue. Messages received with ReceiveAndDelete will be immediately removed from the queue, and cannot be subsequently rejected or re-received if the client fails to process the message. The default mode is PeekLock.
    - idle_timeout (int) – The timeout in seconds between received messages after which the receiver will automatically shutdown. The default value is 0, meaning no timeout.

    Returns: | A Receiver instance with an unopened Connection.
    Return type: | Receiver

    Example

    Receive dead-lettered messages.

        async with queue_client.get_receiver(idle_timeout=5) as receiver:
            async for message in receiver:
                await message.dead_letter()

        async with queue_client.get_deadletter_receiver() as receiver:
            async for message in receiver:
                await message.complete()

  `get_receiver`(session=None, prefetch=0, mode=<ReceiveSettleMode.PeekLock: <ReceiverSettleMode.PeekLock: 1>>, idle_timeout=0, **kwargs)

    Get a Receiver for the Service Bus endpoint.

    A Receiver represents a single open connection with which multiple receive operations can be made.

    Parameters:

    - session (str or NEXT_AVAILABLE) – A specific session from which to receive. This must be specified for a sessionful entity, otherwise it must be None. In order to receive the next available session, set this to NEXT_AVAILABLE.
    - prefetch (int) – The maximum number of messages to cache with each request to the service. The default value is 0, meaning messages will be received from the service and processed one at a time. Increasing this value will improve message throughput performance but increase the chance that messages will expire while they are cached if they’re not processed fast enough.
    - mode (ReceiveSettleMode) – The mode with which messages will be retrieved from the entity. The two options are PeekLock and ReceiveAndDelete. Messages received with PeekLock must be settled within a given lock period before they will be removed from the queue. Messages received with ReceiveAndDelete will be immediately removed from the queue, and cannot be subsequently rejected or re-received if the client fails to process the message. The default mode is PeekLock.
    - idle_timeout (int) – The timeout in seconds between received messages after which the receiver will automatically shutdown. The default value is 0, meaning no timeout.

    Returns: | A Receiver instance with an unopened connection.
    Return type: | Receiver

    Example

    Receive messages with a Receiver.

        async with queue_client.get_receiver() as receiver:
            async for message in receiver:
                await process_message(message)

  `list_sessions`(updated_since=None, max_results=100, skip=0, **kwargs)

    List session IDs.

    List the IDs of sessions in the queue with pending messages and where the state of the session has been updated since the timestamp provided. If no timestamp is provided, all will be returned. If the state of a session has never been set, it will not be returned regardless of whether there are messages pending.

    Parameters:

    - updated_since (datetime) – The UTC datetime from which to return updated pending session IDs.
    - max_results (int) – The maximum number of session IDs to return. Default value is 100.
    - skip (int) – The page value to jump to. Default value is 0.

    Return type: | list[str]

  `peek`(count=1, start_from=0, session=None, **kwargs)

    Browse messages currently pending in the queue.

    Peeked messages are not removed from queue, nor are they locked. They cannot be completed, deferred or dead-lettered.

    Parameters:

    - count (int) – The maximum number of messages to try and peek. The default value is 1.
    - start_from (int) – A message sequence number from which to start browsing messages.
    - session (str) – If the entity requires sessions, a session ID must be supplied in order that only messages from that session will be browsed. If the entity does not require sessions this value will be ignored.

    Return type: | list[PeekMessage]

    Example

    Peek messages in the queue.

        peeked_messages = await queue_client.peek(count=5)

  `receive_deferred_messages`(sequence_numbers, mode=<ReceiveSettleMode.PeekLock: <ReceiverSettleMode.PeekLock: 1>>, **kwargs)

    Receive messages that have previously been deferred.

    When receiving deferred messages from a partitioned entity, all of the supplied sequence numbers must be messages from the same partition.

    Parameters:

    - sequence_numbers (list[int]) – A list of the sequence numbers of messages that have been deferred.
    - mode (ReceiveSettleMode) – The mode with which messages will be retrieved from the entity. The two options are PeekLock and ReceiveAndDelete. Messages received with PeekLock must be settled within a given lock period before they will be removed from the queue. Messages received with ReceiveAndDelete will be immediately removed from the queue, and cannot be subsequently rejected or re-received if the client fails to process the message. The default mode is PeekLock.

    Return type: | list[DeferredMessage]

    Example

    Defer messages, then retrieve them by sequence number.

        sequence_numbers = []
        async with queue_client.get_receiver() as receiver:
            async for message in receiver:
                sequence_numbers.append(message.sequence_number)
                await message.defer()
                break

        deferred = await queue_client.receive_deferred_messages(sequence_numbers)

  `settle_deferred_messages`(settlement, messages, **kwargs)

    Settle messages that have been previously deferred.

    Parameters:

    - settlement (str) – How the messages are to be settled. This must be a string of one of the following values: ‘completed’, ‘suspended’, ‘abandoned’.
    - messages (list[DeferredMessage]) – A list of deferred messages to be settled.

    Example

    Settle deferred messages.

            deferred = await queue_client.receive_deferred_messages(sequence_numbers)

            await queue_client.settle_deferred_messages('completed', deferred)

class `azure.servicebus.aio.async_client.``SendClientMixin`

  Bases: `object`

  `get_sender`(message_timeout=0, session=None, **kwargs)

    Get a Sender for the Service Bus endpoint.

    A Sender represents a single open connection within which multiple send operations can be made.

    Parameters:

    - message_timeout (int) – The period in seconds during which messages sent with this Sender must be sent. If the send is not completed in this time it will fail.
    - session (str or Guid) – An optional session ID. If supplied this session ID will be applied to every outgoing message sent with this Sender. If an individual message already has a session ID, that will be used instead. If no session ID is supplied here, nor set on an outgoing message, a ValueError will be raised if the entity is sessionful.

    Returns: | A Sender instance with an unopened connection.
    Return type: | Sender

    Example

    Send multiple messages with a Sender.

        async with queue_client.get_sender() as sender:

            await sender.send(Message("First"))
            await sender.send(Message("Second"))

  `send`(messages, message_timeout=0, session=None, **kwargs)

    Send one or more messages to the current entity.

    This operation will open a single-use connection, send the supplied messages, and close connection. If the entity requires sessions, a session ID must be either provided here, or set on each outgoing message.

    Parameters:

    - messages (Message or list[Message]) – One or more messages to be sent.
    - message_timeout (int) – The period in seconds during which the Message must be sent. If the send is not completed in this time it will return a failure result.
    - session (str or Guid) – An optional session ID. If supplied this session ID will be applied to every outgoing message sent with this Sender. If an individual message already has a session ID, that will be used instead. If no session ID is supplied here, nor set on an outgoing message, a ValueError will be raised if the entity is sessionful.

    Raises: | ~azure.servicebus.common.errors.MessageSendFailed
    Returns: | A list of the send results of all the messages. Each send result is a tuple with two values. The first is a boolean, indicating True if the message sent, or False if it failed. The second is an error if the message failed, otherwise it will be None.
    Return type: | list[tuple[bool, MessageSendFailed]]

    Example

    Send a single message.

        from azure.servicebus.aio import Message

        message = Message("Hello World")
        await queue_client.send(message)

    Send multiple messages.

        from azure.servicebus.aio import Message

        messages = [Message("First"), Message("Second")]
        await queue_client.send(messages, message_timeout=30)

class `azure.servicebus.aio.async_client.``ServiceBusClient`(*, service_namespace=None, host_base='.servicebus.windows.net', shared_access_key_name=None, shared_access_key_value=None, loop=None, http_request_timeout=65, http_request_session=None, debug=False)

  Bases: `azure.servicebus.common.mixins.ServiceBusMixin`

  A Service Bus client for a namespace with the specified SAS authentication settings.

  Parameters:

  - service_namespace (str) – Service Bus namespace, required for all operations.
  - host_base (str) – Optional. Live host base URL. Defaults to Azure URL.
  - shared_access_key_name (str) – SAS authentication key name.
  - shared_access_key_value (str) – SAS authentication key value.
  - loop – An async event loop.
  - http_request_timeout (int) – Optional. Timeout for the HTTP request, in seconds.
  - http_request_session – Optional. Session object to use for HTTP requests.
  - debug (bool) – Whether to output AMQP network trace to the logger.

  Example

  Create a ServiceBusClient.

      import os
      from azure.servicebus.aio import ServiceBusClient, Message

      namespace = os.environ['SERVICE_BUS_HOSTNAME']
      shared_access_policy = os.environ['SERVICE_BUS_SAS_POLICY']
      shared_access_key = os.environ['SERVICE_BUS_SAS_KEY']

      client = ServiceBusClient(
          service_namespace=namespace,
          shared_access_key_name=shared_access_policy,
          shared_access_key_value=shared_access_key)

  classmethod `from_connection_string`(conn_str, *, loop=None, **kwargs)

    Create a Service Bus client from a connection string.

    Parameters: | conn_str (str) – The connection string.

    Example

    Create a ServiceBusClient via a connection string.

        connection_str = os.environ['SERVICE_BUS_CONNECTION_STR']

        client = ServiceBusClient.from_connection_string(connection_str)

  `get_queue`(queue_name)

    Get an async client for a queue entity.

    Parameters: | queue_name (str) – The name of the queue.
    Return type: | QueueClient
    Raises: | ~azure.servicebus.common.errors.ServiceBusConnectionError if the namespace is not found.
    Raises: | ~azure.servicebus.common.errors.ServiceBusResourceNotFound if the queue is not found.

    Example

    Get a QueueClient for the specified queue.

        from azure.servicebus import ServiceBusResourceNotFound

        try:
            queue_client = client.get_queue("MyQueue")
        except ServiceBusResourceNotFound:
            pass

  `get_subscription`(topic_name, subscription_name)

    Get an async client for a subscription entity.

    Parameters:

    - topic_name (str) – The name of the topic.
    - subscription_name (str) – The name of the subscription.

    Return type: | SubscriptionClient
    Raises: | ~azure.servicebus.common.errors.ServiceBusConnectionError if the namespace is not found.
    Raises: | ~azure.servicebus.common.errors.ServiceBusResourceNotFound if the subscription is not found.

    Example

    Get a TopicClient for the specified topic.

        from azure.servicebus import ServiceBusResourceNotFound

        try:
            subscription_client = client.get_subscription("MyTopic", "MySubscription")
        except ServiceBusResourceNotFound:
            pass

  `get_topic`(topic_name)

    Get an async client for a topic entity.

    Parameters: | topic_name (str) – The name of the topic.
    Return type: | TopicClient
    Raises: | ~azure.servicebus.common.errors.ServiceBusConnectionError if the namespace is not found.
    Raises: | ~azure.servicebus.common.errors.ServiceBusResourceNotFound if the topic is not found.

    Example

    Get a TopicClient for the specified topic.

        from azure.servicebus import ServiceBusResourceNotFound

        try:
            topic_client = client.get_topic("MyTopic")
        except ServiceBusResourceNotFound:
            pass

  `list_queues`()

    Get async clients for all queue entities in the namespace.

    Return type: | list[QueueClient]
    Raises: | ~azure.servicebus.common.errors.ServiceBusConnectionError if the namespace is not found.

  `list_subscriptions`(topic_name)

    Get an async client for all subscription entities in the topic.

    Parameters: | topic_name (str) – The topic to list subscriptions for.
    Return type: | list[SubscriptionClient]
    Raises: | ~azure.servicebus.common.errors.ServiceBusConnectionError if the namespace is not found.
    Raises: | ~azure.servicebus.common.errors.ServiceBusResourceNotFound if the topic is not found.

  `list_topics`()

    Get an async client for all topic entities in the namespace.

    Return type: | list[TopicClient]
    Raises: | ~azure.servicebus.common.errors.ServiceBusConnectionError if the namespace is not found.

class `azure.servicebus.aio.async_client.``SubscriptionClient`(address, name, *, shared_access_key_name=None, shared_access_key_value=None, loop=None, debug=False, **kwargs)

  Bases: `azure.servicebus.aio.async_client.ReceiveClientMixin`, `azure.servicebus.aio.async_client.BaseClient`

  A subscription client.

  The SubscriptionClient class defines a high level interface for receiving messages to an Azure Service Bus Subscription. If you do not wish to perform management operations, a SubscriptionClient can be instantiated directly to perform receive operations from a Subscription.

  Parameters:

  - address (str) – The full URI of the Service Bus namespace. This can optionally include URL-encoded access name and key.
  - name (str) – The name of the topic to which the Client will connect.
  - shared_access_key_name (str) – The name of the shared access policy. This must be supplied if not encoded into the address.
  - shared_access_key_value (str) – The shared access key. This must be supplied if not encoded into the address.
  - loop (EventLoop) – An async event loop
  - debug (bool) – Whether to output network trace logs to the logger. Default is False.

  Example

  Create a SubscriptionClient.

      import os
      from azure.servicebus.aio import SubscriptionClient

      connection_str = os.environ['SERVICE_BUS_CONNECTION_STR']
      subscription_client = SubscriptionClient.from_connection_string(connection_str, name="MySubscription", topic="MyTopic")
      properties = subscription_client.get_properties()

  classmethod `from_connection_string`(conn_str, name, topic=None, **kwargs)

    Create a SubscriptionClient from a connection string.

    Parameters:

    - conn_str (str) – The connection string.
    - name (str) – The name of the Subscription.
    - topic (str) – The name of the Topic, if the EntityName is not included in the connection string.

  classmethod `from_entity`(address, topic, entity, **kwargs)

class `azure.servicebus.aio.async_client.``TopicClient`(address, name, *, shared_access_key_name=None, shared_access_key_value=None, loop=None, debug=False, **kwargs)

  Bases: `azure.servicebus.aio.async_client.SendClientMixin`, `azure.servicebus.aio.async_client.BaseClient`

  A topic client.

  The TopicClient class defines a high level interface for sending messages to an Azure Service Bus Topic. If you do not wish to perform management operations, a TopicClient can be instantiated directly to perform send operations to a Topic.

  Parameters:

  - address (str) – The full URI of the Service Bus namespace. This can optionally include URL-encoded access name and key.
  - name (str) – The name of the topic to which the Client will connect.
  - shared_access_key_name (str) – The name of the shared access policy. This must be supplied if not encoded into the address.
  - shared_access_key_value (str) – The shared access key. This must be supplied if not encoded into the address.
  - loop (EventLoop) – An async event loop
  - debug (bool) – Whether to output network trace logs to the logger. Default is False.

  Example

  Create a TopicClient.

      import os
      from azure.servicebus.aio import TopicClient

      connection_str = os.environ['SERVICE_BUS_CONNECTION_STR']
      topic_client = TopicClient.from_connection_string(connection_str, name="MyTopic")
      topic_properties = topic_client.get_properties()

## azure.servicebus.aio.async_message module

class `azure.servicebus.aio.async_message.``DeferredMessage`(deferred, mode)

  Bases: `azure.servicebus.aio.async_message.Message`

  A message that has been deferred.

  A deferred message can be completed, abandoned, or dead-lettered, however it cannot be deferred again.

  `abandon`()

    Abandon the message. This message will be returned to the queue to be reprocessed.

    Raises: | ~azure.servicebus.common.errors.MessageAlreadySettled if the message has been settled.
    Raises: | ~azure.servicebus.common.errors.MessageLockExpired if message lock has already expired.
    Raises: | ~azure.servicebus.common.errors.MessageSettleFailed if message settle operation fails.

  `complete`()

    Complete the message.

    This removes the message from the queue.

    Raises: | ~azure.servicebus.common.errors.MessageAlreadySettled if the message has been settled.
    Raises: | ~azure.servicebus.common.errors.MessageLockExpired if message lock has already expired.
    Raises: | ~azure.servicebus.common.errors.SessionLockExpired if session lock has already expired.
    Raises: | ~azure.servicebus.common.errors.MessageSettleFailed if message settle operation fails.

  `dead_letter`(description=None)

    Move the message to the Dead Letter queue.

    The Dead Letter queue is a sub-queue that can be used to store messages that failed to process correctly, or otherwise require further inspection or processing. The queue can also be configured to send expired messages to the Dead Letter queue. To receive dead-lettered messages, use QueueClient.get_deadletter_receiver() or SubscriptionClient.get_deadletter_receiver().

    Parameters: | description (str) – The reason for dead-lettering the message.
    Raises: | ~azure.servicebus.common.errors.MessageAlreadySettled if the message has been settled.
    Raises: | ~azure.servicebus.common.errors.MessageLockExpired if message lock has already expired.
    Raises: | ~azure.servicebus.common.errors.MessageSettleFailed if message settle operation fails.

  `defer`()

    A DeferredMessage cannot be deferred. Raises ValueError.

  `lock_token`
  `settled`

    Whether the message has been settled.

    This will aways be True for a message received using ReceiveAndDelete mode, otherwise it will be False until the message is completed or otherwise settled.

    Return type: | bool

class `azure.servicebus.aio.async_message.``Message`(body, *, encoding='UTF-8', loop=None, **kwargs)

  Bases: `azure.servicebus.common.message.Message`

  A Service Bus Message.

  Parameters:

  - body (str or bytes) – The data to send in a single message. The maximum size per message is 256 kB.
  - encoding (str) – The encoding for string data. Default is UTF-8.

  Example

  Sending a message with additional properties

      message = Message("Hello World!")
      message.session_id = "MySessionID"
      message.partition_key = "UsingSpecificPartition"
      message.user_properties = {'data': 'custom_data'}
      message.time_to_live = datetime.timedelta(seconds=30)

      queue_client.send(message)

  Checking the properties on a received message

      with queue_client.get_receiver(idle_timeout=3) as receiver:
          for message in receiver:
              print("Receiving: {}".format(message))
              print("Time to live: {}".format(message.time_to_live))
              print("Sequence number: {}".format(message.sequence_number))
              print("Enqueue Sequence numger: {}".format(message.enqueue_sequence_number))
              print("Partition ID: {}".format(message.partition_id))
              print("Partition Key: {}".format(message.partition_key))
              print("User Properties: {}".format(message.user_properties))
              print("Annotations: {}".format(message.annotations))
              print("Delivery count: {}".format(message.header.delivery_count))
              print("Message ID: {}".format(message.properties.message_id))
              print("Locked until: {}".format(message.locked_until))
              print("Lock Token: {}".format(message.lock_token))
              print("Enqueued time: {}".format(message.enqueued_time))

  `abandon`()

    Abandon the message.

    This message will be returned to the queue to be reprocessed.

    Raises: | ~azure.servicebus.common.errors.MessageAlreadySettled if the message has been settled.
    Raises: | ~azure.servicebus.common.errors.MessageLockExpired if message lock has already expired.
    Raises: | ~azure.servicebus.common.errors.SessionLockExpired if session lock has already expired.
    Raises: | ~azure.servicebus.common.errors.MessageSettleFailed if message settle operation fails.

  `complete`()

    Complete the message. This removes the message from the queue.

    Raises: | ~azure.servicebus.common.errors.MessageAlreadySettled if the message has been settled.
    Raises: | ~azure.servicebus.common.errors.MessageLockExpired if message lock has already expired.
    Raises: | ~azure.servicebus.common.errors.SessionLockExpired if session lock has already expired.
    Raises: | ~azure.servicebus.common.errors.MessageSettleFailed if message settle operation fails.

  `dead_letter`(description=None)

    Move the message to the Dead Letter queue.

    The Dead Letter queue is a sub-queue that can be used to store messages that failed to process correctly, or otherwise require further inspection or processing. The queue can also be configured to send expired messages to the Dead Letter queue. To receive dead-lettered messages, use QueueClient.get_deadletter_receiver() or SubscriptionClient.get_deadletter_receiver().

    Parameters: | description (str) – The reason for dead-lettering the message.
    Raises: | ~azure.servicebus.common.errors.MessageAlreadySettled if the message has been settled.
    Raises: | ~azure.servicebus.common.errors.MessageLockExpired if message lock has already expired.
    Raises: | ~azure.servicebus.common.errors.SessionLockExpired if session lock has already expired.
    Raises: | ~azure.servicebus.common.errors.MessageSettleFailed if message settle operation fails.

  `defer`()

    Defer the message.

    This message will remain in the queue but must be received specifically by its sequence number in order to be processed.

    Raises: | ~azure.servicebus.common.errors.MessageAlreadySettled if the message has been settled.
    Raises: | ~azure.servicebus.common.errors.MessageLockExpired if message lock has already expired.
    Raises: | ~azure.servicebus.common.errors.SessionLockExpired if session lock has already expired.
    Raises: | ~azure.servicebus.common.errors.MessageSettleFailed if message settle operation fails.

  `renew_lock`()

    Renew the message lock.

    This will maintain the lock on the message to ensure it is not returned to the queue to be reprocessed. In order to complete (or otherwise settle) the message, the lock must be maintained. Messages received via ReceiveAndDelete mode are not locked, and therefore cannot be renewed. This operation can also be performed as an asynchronous background task by registering the message with an azure.servicebus.aio.AutoLockRenew instance. This operation is only available for non-sessionful messages.

    Raises: | TypeError if the message is sessionful.
    Raises: | ~azure.servicebus.common.errors.MessageLockExpired is message lock has already expired.
    Raises: | ~azure.servicebus.common.errors.SessionLockExpired if session lock has already expired.
    Raises: | ~azure.servicebus.common.errors.MessageAlreadySettled is message has already been settled.

## azure.servicebus.aio.async_receive_handler module

class `azure.servicebus.aio.async_receive_handler.``Receiver`(handler_id, source, auth_config, *, loop=None, connection=None, mode=<ReceiveSettleMode.PeekLock: <ReceiverSettleMode.PeekLock: 1>>, encoding='UTF-8', debug=False, **kwargs)

  Bases: `collections.abc.AsyncIterator`, `azure.servicebus.aio.async_base_handler.BaseHandler`

  A message receiver.

  This receive handler acts as an iterable message stream for retrieving messages for a Service Bus entity. It operates a single connection that must be opened and closed on completion. The service connection will remain open for the entirety of the iterator. If you find yourself only partially iterating the message stream, you should run the receiver in a with statement to ensure the connection is closed. The Receiver should not be instantiated directly, and should be accessed from a QueueClient or SubscriptionClient using the get_receiver() method.

  Note

  This object is not thread-safe.

  Parameters:

  - handler_id (str) – The ID used as the connection name for the Receiver.
  - source (Source) – The endpoint from which to receive messages.
  - auth_config (dict[str, str]) – The SASL auth credentials.
  - loop (EventLoop) – An async event loop
  - connection (Connection) – A shared connection [not yet supported].
  - mode (ReceiveSettleMode) – The receive connection mode. Value must be either PeekLock or ReceiveAndDelete.
  - encoding (str) – The encoding used for string properties. Default is ‘UTF-8’.
  - debug (bool) – Whether to enable network trace debug logs.

  Example

  Running a queue receiver within a context manager.

      async with queue_client.get_receiver() as receiver:
          async for message in receiver:
              await process_message(message)

  `close`(exception=None)

    Close down the receiver connection.

    If the receiver has already closed, this operation will do nothing. An optional exception can be passed in to indicate that the handler was shutdown due to error. It is recommended to open a handler within a context manager as opposed to calling the method directly. The receiver will be implicitly closed on completion of the message iterator, however this method will need to be called explicitly if the message iterator is not run to completion.

    Note

    This operation is not thread-safe.

    Parameters: | exception (Exception) – An optional exception if the handler is closing due to an error.

    Example

    Iterate then explicitly close a Receiver.

        receiver = queue_client.get_receiver()
        async for message in receiver:
            print(message)
            break
        await receiver.close()

  `fetch_next`(max_batch_size=None, timeout=None)

    Receive a batch of messages at once.

    This approach it optimal if you wish to process multiple messages simultaneously. Note that the number of messages retrieved in a single batch will be dependent on whether prefetch was set for the receiver. This call will prioritize returning quickly over meeting a specified batch size, and so will return as soon as at least one message is received and there is a gap in incoming messages regardless of the specified batch size.

    Parameters:

    - max_batch_size (int) – Maximum number of messages in the batch. Actual number returned will depend on prefetch size and incoming stream rate.
    - timeout – The time to wait in seconds for the first message to arrive. If no messages arrive, and no timeout is specified, this call will not return until the connection is closed. If specified, an no messages arrive within the timeout period, an empty list will be returned.

    Return type: | list[Message]

    Example

    Fetch a batch of messages.

        async with queue_client.get_receiver(idle_timeout=5, prefetch=100) as receiver:
            messages = await receiver.fetch_next(timeout=5)
            await asyncio.gather(*[m.complete() for m in messages])

  `open`()

    Open receiver connection and authenticate session.

    If the receiver is already open, this operation will do nothing. This method will be called automatically when one starts to iterate messages in the receiver, so there should be no need to call it directly. A receiver opened with this method must be explicitly closed. It is recommended to open a handler within a context manager as opposed to calling the method directly.

    Note

    This operation is not thread-safe.

  `peek`(count=1, start_from=0)

    Browse messages currently pending in the queue.

    Peeked messages are not removed from queue, nor are they locked. They cannot be completed, deferred or dead-lettered.

    Parameters:

    - count (int) – The maximum number of messages to try and peek. The default value is 1.
    - start_from (int) – A message sequence number from which to start browsing messages.

    Return type: | list[PeekMessage]

    Example

    Peek messages in the queue.

        async with queue_client.get_receiver() as receiver:
            pending_messages = await receiver.peek(count=5)

  `receive_deferred_messages`(sequence_numbers, mode=<ReceiveSettleMode.PeekLock: <ReceiverSettleMode.PeekLock: 1>>)

    Receive messages that have previously been deferred.

    When receiving deferred messages from a partitioned entity, all of the supplied sequence numbers must be messages from the same partition.

    Parameters:

    - sequence_numbers (list[int]) – A list of the sequence numbers of messages that have been deferred.
    - mode (ReceiveSettleMode) – The receive mode, default value is PeekLock.

    Return type: | list[DeferredMessage]

    Example

    Defer messages, then retrieve them by sequence number.

        async with queue_client.get_receiver() as receiver:
            async for message in receiver:
                sequence_no = message.sequence_number
                await message.defer()
                break

            message = await receiver.receive_deferred_messages([sequence_no])

  `queue_size`

    The current size of the unprocessed message queue.

    Return type: | int

  `receiver_shutdown`

    Whether the receiver connection has been marked for shutdown.

    If this value is True - it does not indicate that the connection has yet been closed. This property is used internally and should not be relied upon to asses the status of the connection.

    Return type: | bool

class `azure.servicebus.aio.async_receive_handler.``SessionReceiver`(handler_id, source, auth_config, *, session=None, loop=None, connection=None, encoding='UTF-8', debug=False, **kwargs)

  Bases: `azure.servicebus.aio.async_receive_handler.Receiver`, `azure.servicebus.common.mixins.SessionMixin`

  A session message receiver.

  This receive handler acts as an iterable message stream for retrieving messages for a sessionful Service Bus entity. It operates a single connection that must be opened and closed on completion. The service connection will remain open for the entirety of the iterator. If you find yourself only partially iterating the message stream, you should run the receiver in a with statement to ensure the connection is closed. The Receiver should not be instantiated directly, and should be accessed from a QueueClient or SubscriptionClient using the get_receiver() method. When receiving messages from a session, connection errors that would normally be automatically retried will instead raise an error due to the loss of the lock on a particular session. A specific session can be specified, or the receiver can retrieve any available session using the NEXT_AVAILABLE constant.

  Note

  This object is not thread-safe.

  Parameters:

  - handler_id (str) – The ID used as the connection name for the Receiver.
  - source (Source) – The endpoint from which to receive messages.
  - auth_config (dict[str, str]) – The SASL auth credentials.
  - session (str or NEXT_AVAILABLE) – The ID of the session to receive from.
  - loop (EventLoop) – An async event loop
  - connection (Connection) – A shared connection [not yet supported].
  - mode (ReceiveSettleMode) – The receive connection mode. Value must be either PeekLock or ReceiveAndDelete.
  - encoding (str) – The encoding used for string properties. Default is ‘UTF-8’.
  - debug (bool) – Whether to enable network trace debug logs.

  Example

  Running a session receiver within a context manager.

      async with queue_client.get_receiver(session="MySessionID") as session:
          async for message in session:
              await process_message(message)

  Running a session receiver for the next available session.

      from azure.servicebus import NEXT_AVAILABLE, NoActiveSession

      try:
          async with queue_client.get_receiver(session=NEXT_AVAILABLE, idle_timeout=5) as receiver:
              async for message in receiver:
                  await process_message(message)
      except NoActiveSession:
          pass

  `get_session_state`()

    Get the session state.

    Returns None if no state has been set.

    Return type: | str

    Example

    Getting and setting the state of a session.

        async with queue_client.get_receiver(session="MySessionID", idle_timeout=5) as session:
            current_state = await session.get_session_state()
            if not current_state:
                await session.set_session_state("OPENED")

  `list_sessions`(updated_since=None, max_results=100, skip=0)

    List session IDs.

    List the IDs of sessions in the queue with pending messages and where the state of the session has been updated since the timestamp provided. If no timestamp is provided, all will be returned. If the state of a session has never been set, it will not be returned regardless of whether there are messages pending.

    Parameters:

    - updated_since (datetime) – The UTC datetime from which to return updated pending session IDs.
    - max_results (int) – The maximum number of session IDs to return. Default value is 100.
    - skip (int) – The page value to jump to. Default value is 0.

    Return type: | list[str]

  `peek`(count=1, start_from=0)

    Browse messages currently pending in the queue.

    Peeked messages are not removed from queue, nor are they locked. They cannot be completed, deferred or dead-lettered. This operation will only peek pending messages in the current session.

    Parameters:

    - count (int) – The maximum number of messages to try and peek. The default value is 1.
    - start_from (int) – A message sequence number from which to start browsing messages.

    Return type: | list[PeekMessage]

    Example

    Peek messages in the queue.

        async with queue_client.get_receiver(session=NEXT_AVAILABLE, idle_timeout=5) as receiver:
            pending_messages = await receiver.peek(count=5)

  `receive_deferred_messages`(sequence_numbers, mode=<ReceiveSettleMode.PeekLock: <ReceiverSettleMode.PeekLock: 1>>)

    Receive messages that have previously been deferred.

    This operation can only receive deferred messages from the current session. When receiving deferred messages from a partitioned entity, all of the supplied sequence numbers must be messages from the same partition.

    Parameters:

    - sequence_numbers (list[int]) – A list of the sequence numbers of messages that have been deferred.
    - mode (ReceiveSettleMode) – The receive mode, default value is PeekLock.

    Return type: | list[DeferredMessage]

    Example

    Defer messages, then retrieve them by sequence number.

        async with queue_client.get_receiver(session="MySessionID", idle_timeout=5) as receiver:
            sequence_numbers = []
            async for message in receiver:
                sequence_numbers.append(message.sequence_number)
                await message.defer()
                break

            message = await receiver.receive_deferred_messages(sequence_numbers)

  `renew_lock`()

    Renew the session lock.

    This operation must be performed periodically in order to retain a lock on the session to continue message processing. Once the lock is lost the connection will be closed. This operation can also be performed as an asynchronous background task by registering the session with an azure.servicebus.aio.AutoLockRenew instance.

    Example

    Renew the sesison lock.

        async with queue_client.get_receiver(session="MySessionID", idle_timeout=5) as session:
            async for message in session:
                await process_message(message)
                await session.renew_lock()

  `set_session_state`(state)

    Set the session state.

    Parameters: | state (str or bytes or bytearray) – The state value.

    Example

    Getting and setting the state of a session.

        async with queue_client.get_receiver(session="MySessionID", idle_timeout=5) as session:
            current_state = await session.get_session_state()
            if not current_state:
                await session.set_session_state("OPENED")

## azure.servicebus.aio.async_send_handler module

class `azure.servicebus.aio.async_send_handler.``Sender`(handler_id, target, auth_config, *, session=None, loop=None, connection=None, encoding='UTF-8', debug=False, **kwargs)

  Bases: `azure.servicebus.aio.async_base_handler.BaseHandler`, `azure.servicebus.common.mixins.SenderMixin`

  This handler is for sending messages to a Service Bus entity.

  It operates a single connection that must be opened and closed on completion. The Sender can be run within a context manager to ensure that the connection is closed on exit. The Sender should not be instantiated directly, and should be accessed from a QueueClient or TopicClient using the get_sender() method.

  Note

  This object is not thread-safe.

  Parameters:

  - handler_id (str) – The ID used as the connection name for the Sender.
  - target (Target) – The endpoint to send messages to.
  - auth_config (dict[str, str]) – The SASL auth credentials.
  - session (str) – An optional session ID. If supplied, all outgoing messages will have this session ID added (unless they already have one specified).
  - loop (EventLoop) – An async event loop
  - connection (Connection) – A shared connection [not yet supported].
  - encoding (str) – The encoding used for string properties. Default is ‘UTF-8’.
  - debug (bool) – Whether to enable network trace debug logs.

  `cancel_scheduled_messages`(*sequence_numbers)

    Cancel one or more messages that have previsouly been scheduled and are still pending.

    Parameters: | sequence_numbers (int) – The seqeuence numbers of the scheduled messages.

    Example

    Schedule messages.

        async with queue_client.get_sender() as sender:

            enqueue_time = datetime.utcnow() + timedelta(minutes=10)
            sequence_numbers = await sender.schedule(enqueue_time, Message("First"), Message("Second"))

            await sender.cancel_scheduled_messages(*sequence_numbers)

  `reconnect`()

    Reconnect the handler.

    If the handler was disconnected from the service with a retryable error - attempt to reconnect. This method will be called automatically for most retryable errors. Also attempts to re-queue any messages that were pending before the reconnect.

  `schedule`(schedule_time, *messages)

    Send one or more messages to be enqueued at a specific time.

    Returns a list of the sequence numbers of the enqueued messages.

    Parameters:

    - schedule_time (datetime) – The date and time to enqueue the messages.
    - messages (Message) – The messages to schedule.

    Return type: | list[int]

    Example

    Schedule messages.

        async with queue_client.get_sender() as sender:

            enqueue_time = datetime.utcnow() + timedelta(minutes=10)
            await sender.schedule(enqueue_time, Message("First"), Message("Second"))

  `send`(message)

    Send a message and blocks until acknowledgement is received or the operation fails.

    Parameters: | message (Message) – The message to be sent.
    Raises: | ~azure.servicebus.common.errors.MessageSendFailed if the message fails to send.

    Example

    Open a Sender and send messages.

        async with queue_client.get_sender() as sender:

            await sender.send(Message("First"))
            await sender.send(Message("Second"))

  `send_pending_messages`()

    Wait until all pending messages have been sent.

    Returns: | A list of the send results of all the pending messages. Each send result is a tuple with two values. The first is a boolean, indicating True if the message sent, or False if it failed. The second is an error if the message failed, otherwise it will be None.
    Return type: | list[tuple[bool, MessageSendFailed]]

    Example

    Schedule messages.

        async with queue_client.get_sender() as sender:

            sender.queue_message(Message("First"))
            sender.queue_message(Message("Second"))
            await sender.send_pending_messages()

class `azure.servicebus.aio.async_send_handler.``SessionSender`(handler_id, target, auth_config, *, session=None, loop=None, connection=None, encoding='UTF-8', debug=False, **kwargs)

  Bases: `azure.servicebus.aio.async_send_handler.Sender`

  This handler is for sending messages to a sessionful Service Bus entity.

  It operates a single connection that must be opened and closed on completion. The Sender can be run within a context manager to ensure that the connection is closed on exit. The Sender should not be instantiated directly, and should be accessed from a QueueClient or TopicClient using the get_sender() method. An attempt to send a message without a session ID specified either on the Sender or the message will raise a ValueError.

  Note

  This object is not thread-safe.

  Parameters:

  - handler_id (str) – The ID used as the connection name for the Sender.
  - target (Target) – The endpoint to send messages to.
  - auth_config (dict[str, str]) – The SASL auth credentials.
  - session (str) – An optional session ID. If supplied, all outgoing messages will have this session ID added (unless they already have one specified).
  - loop (EventLoop) – An async event loop
  - connection (Connection) – A shared connection [not yet supported].
  - encoding (str) – The encoding used for string properties. Default is ‘UTF-8’.
  - debug (bool) – Whether to enable network trace debug logs.

  `queue_message`(message)

    Queue a message to be sent later.

    This operation should be followed up with send_pending_messages. If neither the Sender nor the message has a session ID, a ValueError will be raised.

    Parameters: | message (Message) – The message to be sent.

    Example

    Schedule messages.

        async with queue_client.get_sender(session="MySessionID") as sender:

            sender.queue_message(Message("First"))
            sender.queue_message(Message("Second"))
            await sender.send_pending_messages()

  `schedule_messages`(schedule_time, *messages)

    Send one or more messages to be enqueued at a specific time.

    Returns a list of the sequence numbers of the enqueued messages. If neither the Sender nor the message has a session ID, a ValueError will be raised.

    Parameters:

    - schedule_time (datetime) – The date and time to enqueue the messages.
    - messages (Message) – The messages to schedule.

    Return type: | list[int]

    Example

    Schedule messages.

        async with queue_client.get_sender(session="MySessionID") as sender:

            enqueue_time = datetime.utcnow() + timedelta(minutes=10)
            await sender.schedule(enqueue_time, Message("First"), Message("Second"))

  `send`(message)

    Send a message and blocks until acknowledgement is received or the operation fails.

    If neither the Sender nor the message has a session ID, a ValueError will be raised.

    Parameters: | message (Message) – The message to be sent.
    Raises: | ~azure.servicebus.common.errors.MessageSendFailed if the message fails to send.

    Example

    Open a sessionful Sender and send messages.

        from azure.servicebus.aio import Message

        async with queue_client.get_sender(session="MySessionID") as sender:

            await sender.send(Message("First"))
            await sender.send(Message("Second"))

## azure.servicebus.aio.async_utils module

class `azure.servicebus.aio.async_utils.``AutoLockRenew`(loop=None)

  Bases: `object`

  Auto lock renew.

  An asynchronous AutoLockRenew handler for renewing the lock tokens of messages and/or sessions in the background.

  Parameters: | loop (EventLoop) – An async event loop.

  Example

  Automatically renew a message lock

      from azure.servicebus.aio import AutoLockRenew

      lock_renewal = AutoLockRenew()
      async with queue_client.get_receiver(idle_timeout=3) as queue_receiver:
          async for message in queue_receiver:
              lock_renewal.register(message, timeout=60)
              await process_message(message)

              await message.complete()

  Automatically renew a session lock

      from azure.servicebus.aio import AutoLockRenew

      lock_renewal = AutoLockRenew()
      async with queue_client.get_receiver(session="MySessionID", idle_timeout=3) as session:
          lock_renewal.register(session)

          async for message in session:
              await process_message(message)
              await message.complete()

  `register`(renewable, timeout=300)

    Register a renewable entity for automatic lock renewal.

    Parameters:

    - renewable (Message or SessionReceiver) – A locked entity that needs to be renewed.
    - timeout (int) – A time in seconds that the lock should be maintained for. Default value is 300 (5 minutes).

  `shutdown`()

    Cancel remaining open lock renewal futures.

## Module contents

exception `azure.servicebus.aio.``ServiceBusError`(message, inner_exception=None)

  Bases: `Exception`

  An error occured.

  This is the parent of all Service Bus errors and can be used for default error handling.

exception `azure.servicebus.aio.``ServiceBusResourceNotFound`(message, inner_exception=None)

  Bases: `azure.servicebus.common.errors.ServiceBusError`

  The Service Bus entity could not be reached.

exception `azure.servicebus.aio.``ServiceBusConnectionError`(message, inner_exception=None)

  Bases: `azure.servicebus.common.errors.ServiceBusError`

  An error occured in the connection.

exception `azure.servicebus.aio.``ServiceBusAuthorizationError`(message, inner_exception=None)

  Bases: `azure.servicebus.common.errors.ServiceBusError`

  An error occured when authorizing the connection.

exception `azure.servicebus.aio.``InvalidHandlerState`(message, inner_exception=None)

  Bases: `azure.servicebus.common.errors.ServiceBusError`

  An attempt to run a handler operation that the handler is not in the right state to perform.

exception `azure.servicebus.aio.``NoActiveSession`(message, inner_exception=None)

  Bases: `azure.servicebus.common.errors.ServiceBusError`

  No active Sessions are available to receive from.

exception `azure.servicebus.aio.``MessageAlreadySettled`(action)

  Bases: `azure.servicebus.common.errors.ServiceBusError`

  Failed to settle the message.

  An attempt was made to complete an operation on a message that has already been settled (completed, abandoned, dead-lettered or deferred). This error will also be raised if an attempt is made to settle a message received via ReceiveAndDelete mode.

exception `azure.servicebus.aio.``MessageSettleFailed`(action, inner_exception)

  Bases: `azure.servicebus.common.errors.ServiceBusError`

  Attempt to settle a message failed.

exception `azure.servicebus.aio.``MessageSendFailed`(inner_exception)

  Bases: `azure.servicebus.common.errors.ServiceBusError`

  A message failed to send to the Service Bus entity.

exception `azure.servicebus.aio.``MessageLockExpired`(message=None, inner_exception=None)

  Bases: `azure.servicebus.common.errors.ServiceBusError`

  The lock on the message has expired and it has been released back to the queue.

  It will need to be received again in order to settle it.

exception `azure.servicebus.aio.``SessionLockExpired`(message=None, inner_exception=None)

  Bases: `azure.servicebus.common.errors.ServiceBusError`

  The lock on the session has expired.

  All unsettled messages that have been received can no longer be settled.

exception `azure.servicebus.aio.``AutoLockRenewFailed`(message, inner_exception=None)

  Bases: `azure.servicebus.common.errors.ServiceBusError`

  An attempt to renew a lock on a message or session in the background has failed.

exception `azure.servicebus.aio.``AutoLockRenewTimeout`(message, inner_exception=None)

  Bases: `azure.servicebus.common.errors.ServiceBusError`

  The time allocated to renew the message or session lock has elapsed.

class `azure.servicebus.aio.``Message`(body, *, encoding='UTF-8', loop=None, **kwargs)

  Bases: `azure.servicebus.common.message.Message`

  A Service Bus Message.

  Parameters:

  - body (str or bytes) – The data to send in a single message. The maximum size per message is 256 kB.
  - encoding (str) – The encoding for string data. Default is UTF-8.

  Example

  Sending a message with additional properties

      message = Message("Hello World!")
      message.session_id = "MySessionID"
      message.partition_key = "UsingSpecificPartition"
      message.user_properties = {'data': 'custom_data'}
      message.time_to_live = datetime.timedelta(seconds=30)

      queue_client.send(message)

  Checking the properties on a received message

      with queue_client.get_receiver(idle_timeout=3) as receiver:
          for message in receiver:
              print("Receiving: {}".format(message))
              print("Time to live: {}".format(message.time_to_live))
              print("Sequence number: {}".format(message.sequence_number))
              print("Enqueue Sequence numger: {}".format(message.enqueue_sequence_number))
              print("Partition ID: {}".format(message.partition_id))
              print("Partition Key: {}".format(message.partition_key))
              print("User Properties: {}".format(message.user_properties))
              print("Annotations: {}".format(message.annotations))
              print("Delivery count: {}".format(message.header.delivery_count))
              print("Message ID: {}".format(message.properties.message_id))
              print("Locked until: {}".format(message.locked_until))
              print("Lock Token: {}".format(message.lock_token))
              print("Enqueued time: {}".format(message.enqueued_time))

  `abandon`()

    Abandon the message.

    This message will be returned to the queue to be reprocessed.

    Raises: | ~azure.servicebus.common.errors.MessageAlreadySettled if the message has been settled.
    Raises: | ~azure.servicebus.common.errors.MessageLockExpired if message lock has already expired.
    Raises: | ~azure.servicebus.common.errors.SessionLockExpired if session lock has already expired.
    Raises: | ~azure.servicebus.common.errors.MessageSettleFailed if message settle operation fails.

  `complete`()

    Complete the message. This removes the message from the queue.

    Raises: | ~azure.servicebus.common.errors.MessageAlreadySettled if the message has been settled.
    Raises: | ~azure.servicebus.common.errors.MessageLockExpired if message lock has already expired.
    Raises: | ~azure.servicebus.common.errors.SessionLockExpired if session lock has already expired.
    Raises: | ~azure.servicebus.common.errors.MessageSettleFailed if message settle operation fails.

  `dead_letter`(description=None)

    Move the message to the Dead Letter queue.

    The Dead Letter queue is a sub-queue that can be used to store messages that failed to process correctly, or otherwise require further inspection or processing. The queue can also be configured to send expired messages to the Dead Letter queue. To receive dead-lettered messages, use QueueClient.get_deadletter_receiver() or SubscriptionClient.get_deadletter_receiver().

    Parameters: | description (str) – The reason for dead-lettering the message.
    Raises: | ~azure.servicebus.common.errors.MessageAlreadySettled if the message has been settled.
    Raises: | ~azure.servicebus.common.errors.MessageLockExpired if message lock has already expired.
    Raises: | ~azure.servicebus.common.errors.SessionLockExpired if session lock has already expired.
    Raises: | ~azure.servicebus.common.errors.MessageSettleFailed if message settle operation fails.

  `defer`()

    Defer the message.

    This message will remain in the queue but must be received specifically by its sequence number in order to be processed.

    Raises: | ~azure.servicebus.common.errors.MessageAlreadySettled if the message has been settled.
    Raises: | ~azure.servicebus.common.errors.MessageLockExpired if message lock has already expired.
    Raises: | ~azure.servicebus.common.errors.SessionLockExpired if session lock has already expired.
    Raises: | ~azure.servicebus.common.errors.MessageSettleFailed if message settle operation fails.

  `renew_lock`()

    Renew the message lock.

    This will maintain the lock on the message to ensure it is not returned to the queue to be reprocessed. In order to complete (or otherwise settle) the message, the lock must be maintained. Messages received via ReceiveAndDelete mode are not locked, and therefore cannot be renewed. This operation can also be performed as an asynchronous background task by registering the message with an azure.servicebus.aio.AutoLockRenew instance. This operation is only available for non-sessionful messages.

    Raises: | TypeError if the message is sessionful.
    Raises: | ~azure.servicebus.common.errors.MessageLockExpired is message lock has already expired.
    Raises: | ~azure.servicebus.common.errors.SessionLockExpired if session lock has already expired.
    Raises: | ~azure.servicebus.common.errors.MessageAlreadySettled is message has already been settled.

class `azure.servicebus.aio.``AutoLockRenew`(loop=None)

  Bases: `object`

  Auto lock renew.

  An asynchronous AutoLockRenew handler for renewing the lock tokens of messages and/or sessions in the background.

  Parameters: | loop (EventLoop) – An async event loop.

  Example

  Automatically renew a message lock

      from azure.servicebus.aio import AutoLockRenew

      lock_renewal = AutoLockRenew()
      async with queue_client.get_receiver(idle_timeout=3) as queue_receiver:
          async for message in queue_receiver:
              lock_renewal.register(message, timeout=60)
              await process_message(message)

              await message.complete()

  Automatically renew a session lock

      from azure.servicebus.aio import AutoLockRenew

      lock_renewal = AutoLockRenew()
      async with queue_client.get_receiver(session="MySessionID", idle_timeout=3) as session:
          lock_renewal.register(session)

          async for message in session:
              await process_message(message)
              await message.complete()

  `register`(renewable, timeout=300)

    Register a renewable entity for automatic lock renewal.

    Parameters:

    - renewable (Message or SessionReceiver) – A locked entity that needs to be renewed.
    - timeout (int) – A time in seconds that the lock should be maintained for. Default value is 300 (5 minutes).

  `shutdown`()

    Cancel remaining open lock renewal futures.

class `azure.servicebus.aio.``BatchMessage`(body, encoding='UTF-8', **kwargs)

  Bases: `azure.servicebus.common.message.Message`

  A batch of messages combined into a single message body.

  The body of the messages in the batch should be supplied by an iterable, such as a generator. If the contents of the iterable exceeds the maximum size of a single message (256 kB), the data will be broken up across multiple messages.

  Parameters:

  - body (Iterable) – The data to send in each message in the batch. The maximum size per message is 256 kB. If data is supplied in excess of this limit, multiple messages will be sent.
  - encoding (str) – The encoding for string data. Default is UTF-8.

  Example

  Send a batched message.

      from azure.servicebus import BatchMessage

      def batched_data():
          for i in range(100):
              yield "Batched Message no. {}".format(i)

      message = BatchMessage(batched_data())
      results = queue_client.send(message)

class `azure.servicebus.aio.``PeekMessage`(message)

  Bases: `azure.servicebus.common.message.Message`

  A preview message.

  This message is still on the queue, and unlocked. A peeked message cannot be completed, abandoned, dead-lettered or deferred. It has no lock token or expiry.

  `abandon`()

    A PeekMessage cannot be abandoned. Raises TypeError.

  `complete`()

    A PeekMessage cannot be completed Raises TypeError.

  `dead_letter`(description=None)

    A PeekMessage cannot be dead-lettered. Raises TypeError.

  `defer`()

    A PeekMessage cannot be deferred. Raises TypeError.

  `renew_lock`()

    A PeekMessage cannot be renewed. Raises TypeError.

  `lock_token`
  `locked_until`

class `azure.servicebus.aio.``DeferredMessage`(deferred, mode)

  Bases: `azure.servicebus.aio.async_message.Message`

  A message that has been deferred.

  A deferred message can be completed, abandoned, or dead-lettered, however it cannot be deferred again.

  `abandon`()

    Abandon the message. This message will be returned to the queue to be reprocessed.

    Raises: | ~azure.servicebus.common.errors.MessageAlreadySettled if the message has been settled.
    Raises: | ~azure.servicebus.common.errors.MessageLockExpired if message lock has already expired.
    Raises: | ~azure.servicebus.common.errors.MessageSettleFailed if message settle operation fails.

  `complete`()

    Complete the message.

    This removes the message from the queue.

    Raises: | ~azure.servicebus.common.errors.MessageAlreadySettled if the message has been settled.
    Raises: | ~azure.servicebus.common.errors.MessageLockExpired if message lock has already expired.
    Raises: | ~azure.servicebus.common.errors.SessionLockExpired if session lock has already expired.
    Raises: | ~azure.servicebus.common.errors.MessageSettleFailed if message settle operation fails.

  `dead_letter`(description=None)

    Move the message to the Dead Letter queue.

    The Dead Letter queue is a sub-queue that can be used to store messages that failed to process correctly, or otherwise require further inspection or processing. The queue can also be configured to send expired messages to the Dead Letter queue. To receive dead-lettered messages, use QueueClient.get_deadletter_receiver() or SubscriptionClient.get_deadletter_receiver().

    Parameters: | description (str) – The reason for dead-lettering the message.
    Raises: | ~azure.servicebus.common.errors.MessageAlreadySettled if the message has been settled.
    Raises: | ~azure.servicebus.common.errors.MessageLockExpired if message lock has already expired.
    Raises: | ~azure.servicebus.common.errors.MessageSettleFailed if message settle operation fails.

  `defer`()

    A DeferredMessage cannot be deferred. Raises ValueError.

  `lock_token`
  `settled`

    Whether the message has been settled.

    This will aways be True for a message received using ReceiveAndDelete mode, otherwise it will be False until the message is completed or otherwise settled.

    Return type: | bool

class `azure.servicebus.aio.``ServiceBusClient`(*, service_namespace=None, host_base='.servicebus.windows.net', shared_access_key_name=None, shared_access_key_value=None, loop=None, http_request_timeout=65, http_request_session=None, debug=False)

  Bases: `azure.servicebus.common.mixins.ServiceBusMixin`

  A Service Bus client for a namespace with the specified SAS authentication settings.

  Parameters:

  - service_namespace (str) – Service Bus namespace, required for all operations.
  - host_base (str) – Optional. Live host base URL. Defaults to Azure URL.
  - shared_access_key_name (str) – SAS authentication key name.
  - shared_access_key_value (str) – SAS authentication key value.
  - loop – An async event loop.
  - http_request_timeout (int) – Optional. Timeout for the HTTP request, in seconds.
  - http_request_session – Optional. Session object to use for HTTP requests.
  - debug (bool) – Whether to output AMQP network trace to the logger.

  Example

  Create a ServiceBusClient.

      import os
      from azure.servicebus.aio import ServiceBusClient, Message

      namespace = os.environ['SERVICE_BUS_HOSTNAME']
      shared_access_policy = os.environ['SERVICE_BUS_SAS_POLICY']
      shared_access_key = os.environ['SERVICE_BUS_SAS_KEY']

      client = ServiceBusClient(
          service_namespace=namespace,
          shared_access_key_name=shared_access_policy,
          shared_access_key_value=shared_access_key)

  classmethod `from_connection_string`(conn_str, *, loop=None, **kwargs)

    Create a Service Bus client from a connection string.

    Parameters: | conn_str (str) – The connection string.

    Example

    Create a ServiceBusClient via a connection string.

        connection_str = os.environ['SERVICE_BUS_CONNECTION_STR']

        client = ServiceBusClient.from_connection_string(connection_str)

  `get_queue`(queue_name)

    Get an async client for a queue entity.

    Parameters: | queue_name (str) – The name of the queue.
    Return type: | QueueClient
    Raises: | ~azure.servicebus.common.errors.ServiceBusConnectionError if the namespace is not found.
    Raises: | ~azure.servicebus.common.errors.ServiceBusResourceNotFound if the queue is not found.

    Example

    Get a QueueClient for the specified queue.

        from azure.servicebus import ServiceBusResourceNotFound

        try:
            queue_client = client.get_queue("MyQueue")
        except ServiceBusResourceNotFound:
            pass

  `get_subscription`(topic_name, subscription_name)

    Get an async client for a subscription entity.

    Parameters:

    - topic_name (str) – The name of the topic.
    - subscription_name (str) – The name of the subscription.

    Return type: | SubscriptionClient
    Raises: | ~azure.servicebus.common.errors.ServiceBusConnectionError if the namespace is not found.
    Raises: | ~azure.servicebus.common.errors.ServiceBusResourceNotFound if the subscription is not found.

    Example

    Get a TopicClient for the specified topic.

        from azure.servicebus import ServiceBusResourceNotFound

        try:
            subscription_client = client.get_subscription("MyTopic", "MySubscription")
        except ServiceBusResourceNotFound:
            pass

  `get_topic`(topic_name)

    Get an async client for a topic entity.

    Parameters: | topic_name (str) – The name of the topic.
    Return type: | TopicClient
    Raises: | ~azure.servicebus.common.errors.ServiceBusConnectionError if the namespace is not found.
    Raises: | ~azure.servicebus.common.errors.ServiceBusResourceNotFound if the topic is not found.

    Example

    Get a TopicClient for the specified topic.

        from azure.servicebus import ServiceBusResourceNotFound

        try:
            topic_client = client.get_topic("MyTopic")
        except ServiceBusResourceNotFound:
            pass

  `list_queues`()

    Get async clients for all queue entities in the namespace.

    Return type: | list[QueueClient]
    Raises: | ~azure.servicebus.common.errors.ServiceBusConnectionError if the namespace is not found.

  `list_subscriptions`(topic_name)

    Get an async client for all subscription entities in the topic.

    Parameters: | topic_name (str) – The topic to list subscriptions for.
    Return type: | list[SubscriptionClient]
    Raises: | ~azure.servicebus.common.errors.ServiceBusConnectionError if the namespace is not found.
    Raises: | ~azure.servicebus.common.errors.ServiceBusResourceNotFound if the topic is not found.

  `list_topics`()

    Get an async client for all topic entities in the namespace.

    Return type: | list[TopicClient]
    Raises: | ~azure.servicebus.common.errors.ServiceBusConnectionError if the namespace is not found.

class `azure.servicebus.aio.``QueueClient`(address, name, *, shared_access_key_name=None, shared_access_key_value=None, loop=None, debug=False, **kwargs)

  Bases: `azure.servicebus.aio.async_client.SendClientMixin`, `azure.servicebus.aio.async_client.ReceiveClientMixin`, `azure.servicebus.aio.async_client.BaseClient`

  A queue client.

  The QueueClient class defines a high level interface for sending messages to and receiving messages from an Azure Service Bus queue. If you do not wish to perform management operations, a QueueClient can be instantiated directly to perform send and receive operations to a Queue. However if a QueueClient is created directly, a get_properties operation will need to be completed in order to retrieve the properties of this queue (for example, whether it is sessionful).

  Parameters:

  - address (str) – The full URI of the Service Bus namespace. This can optionally include URL-encoded access name and key.
  - name (str) – The name of the queue to which the Client will connect.
  - shared_access_key_name (str) – The name of the shared access policy. This must be supplied if not encoded into the address.
  - shared_access_key_value (str) – The shared access key. This must be supplied if not encoded into the address.
  - loop (EventLoop) – An async event loop
  - debug (bool) – Whether to output network trace logs to the logger. Default is False.

  Example

  Create a QueueClient.

      import os
      from azure.servicebus.aio import QueueClient

      connection_str = os.environ['SERVICE_BUS_CONNECTION_STR']
      queue_client = QueueClient.from_connection_string(connection_str, name="MyQueue")
      queue_properties = queue_client.get_properties()

class `azure.servicebus.aio.``TopicClient`(address, name, *, shared_access_key_name=None, shared_access_key_value=None, loop=None, debug=False, **kwargs)

  Bases: `azure.servicebus.aio.async_client.SendClientMixin`, `azure.servicebus.aio.async_client.BaseClient`

  A topic client.

  The TopicClient class defines a high level interface for sending messages to an Azure Service Bus Topic. If you do not wish to perform management operations, a TopicClient can be instantiated directly to perform send operations to a Topic.

  Parameters:

  - address (str) – The full URI of the Service Bus namespace. This can optionally include URL-encoded access name and key.
  - name (str) – The name of the topic to which the Client will connect.
  - shared_access_key_name (str) – The name of the shared access policy. This must be supplied if not encoded into the address.
  - shared_access_key_value (str) – The shared access key. This must be supplied if not encoded into the address.
  - loop (EventLoop) – An async event loop
  - debug (bool) – Whether to output network trace logs to the logger. Default is False.

  Example

  Create a TopicClient.

      import os
      from azure.servicebus.aio import TopicClient

      connection_str = os.environ['SERVICE_BUS_CONNECTION_STR']
      topic_client = TopicClient.from_connection_string(connection_str, name="MyTopic")
      topic_properties = topic_client.get_properties()

class `azure.servicebus.aio.``SubscriptionClient`(address, name, *, shared_access_key_name=None, shared_access_key_value=None, loop=None, debug=False, **kwargs)

  Bases: `azure.servicebus.aio.async_client.ReceiveClientMixin`, `azure.servicebus.aio.async_client.BaseClient`

  A subscription client.

  The SubscriptionClient class defines a high level interface for receiving messages to an Azure Service Bus Subscription. If you do not wish to perform management operations, a SubscriptionClient can be instantiated directly to perform receive operations from a Subscription.

  Parameters:

  - address (str) – The full URI of the Service Bus namespace. This can optionally include URL-encoded access name and key.
  - name (str) – The name of the topic to which the Client will connect.
  - shared_access_key_name (str) – The name of the shared access policy. This must be supplied if not encoded into the address.
  - shared_access_key_value (str) – The shared access key. This must be supplied if not encoded into the address.
  - loop (EventLoop) – An async event loop
  - debug (bool) – Whether to output network trace logs to the logger. Default is False.

  Example

  Create a SubscriptionClient.

      import os
      from azure.servicebus.aio import SubscriptionClient

      connection_str = os.environ['SERVICE_BUS_CONNECTION_STR']
      subscription_client = SubscriptionClient.from_connection_string(connection_str, name="MySubscription", topic="MyTopic")
      properties = subscription_client.get_properties()

  classmethod `from_connection_string`(conn_str, name, topic=None, **kwargs)

    Create a SubscriptionClient from a connection string.

    Parameters:

    - conn_str (str) – The connection string.
    - name (str) – The name of the Subscription.
    - topic (str) – The name of the Topic, if the EntityName is not included in the connection string.

  classmethod `from_entity`(address, topic, entity, **kwargs)

class `azure.servicebus.aio.``ReceiveSettleMode`

  Bases: `enum.Enum`

  An enumeration.

  `PeekLock` = <ReceiverSettleMode.PeekLock: 1>
  `ReceiveAndDelete` = <ReceiverSettleMode.ReceiveAndDelete: 0>