azure.servicebus package

exception azure.servicebus.ServiceBusError(message, inner_exception=None)[source]

An error occured.

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

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

args
exception azure.servicebus.ServiceBusResourceNotFound(message, inner_exception=None)[source]

The Service Bus entity could not be reached.

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

args
exception azure.servicebus.ServiceBusConnectionError(message, inner_exception=None)[source]

An error occured in the connection.

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

args
exception azure.servicebus.ServiceBusAuthorizationError(message, inner_exception=None)[source]

An error occured when authorizing the connection.

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

args
exception azure.servicebus.InvalidHandlerState(message, inner_exception=None)[source]

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

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

args
exception azure.servicebus.NoActiveSession(message, inner_exception=None)[source]

No active Sessions are available to receive from.

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

args
exception azure.servicebus.MessageAlreadySettled(action)[source]

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.

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

args
exception azure.servicebus.MessageSettleFailed(action, inner_exception)[source]

Attempt to settle a message failed.

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

args
exception azure.servicebus.MessageSendFailed(inner_exception)[source]

A message failed to send to the Service Bus entity.

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

args
exception azure.servicebus.MessageLockExpired(message=None, inner_exception=None)[source]

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.

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

args
exception azure.servicebus.SessionLockExpired(message=None, inner_exception=None)[source]

The lock on the session has expired.

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

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

args
exception azure.servicebus.AutoLockRenewFailed(message, inner_exception=None)[source]

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

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

args
exception azure.servicebus.AutoLockRenewTimeout(message, inner_exception=None)[source]

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

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

args
class azure.servicebus.Message(body, encoding='UTF-8', **kwargs)[source]

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: .. literalinclude:: ../samples/sync_samples/test_examples.py :start-after: [START send_complex_message] :end-before: [END send_complex_message] :language: python :dedent: 4 :caption: Sending a message with additional properties

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

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

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, reason=None)[source]

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 error description for dead-lettering the message.

  • reason (str) – The reason for dead-lettering the message. If reason is not set while description is set, then reason would be set the same as description.

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

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

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 a threaded background task by registering the message with an azure.servicebus.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.MessageAlreadySettled is message has already been settled.

schedule(schedule_time)[source]

Add a specific enqueue time to the message.

Parameters

schedule_time (datetime) – The scheduled time to enqueue the message.

property annotations

The annotations of the message.

Return type

dict

property body

The body of the Message.

Return type

bytes or generator[bytes]

property enqueue_sequence_number
property enqueued_time
property expired
property lock_token
property locked_until
property partition_id
property partition_key
property scheduled_enqueue_time
property sequence_number
property session_id
property 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

property time_to_live
property user_properties

User defined properties on the message.

Return type

dict

property via_partition_key
class azure.servicebus.BatchMessage(body, encoding='UTF-8', **kwargs)[source]

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.

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, reason=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 error description for dead-lettering the message.

  • reason (str) – The reason for dead-lettering the message. If reason is not set while description is set, then reason would be set the same as description.

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 a threaded background task by registering the message with an azure.servicebus.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.MessageAlreadySettled is message has already been settled.

schedule(schedule_time)

Add a specific enqueue time to the message.

Parameters

schedule_time (datetime) – The scheduled time to enqueue the message.

property annotations

The annotations of the message.

Return type

dict

property body

The body of the Message.

Return type

bytes or generator[bytes]

property enqueue_sequence_number
property enqueued_time
property expired
property lock_token
property locked_until
property partition_id
property partition_key
property scheduled_enqueue_time
property sequence_number
property session_id
property 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

property time_to_live
property user_properties

User defined properties on the message.

Return type

dict

property via_partition_key
class azure.servicebus.PeekMessage(message)[source]

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

A PeekMessage cannot be abandoned. Raises TypeError.

complete()[source]

A PeekMessage cannot be completed Raises TypeError.

dead_letter(description=None, reason=None)[source]

A PeekMessage cannot be dead-lettered. Raises TypeError.

defer()[source]

A PeekMessage cannot be deferred. Raises TypeError.

renew_lock()[source]

A PeekMessage cannot be renewed. Raises TypeError.

schedule(schedule_time)

Add a specific enqueue time to the message.

Parameters

schedule_time (datetime) – The scheduled time to enqueue the message.

property annotations

The annotations of the message.

Return type

dict

property body

The body of the Message.

Return type

bytes or generator[bytes]

property enqueue_sequence_number
property enqueued_time
property expired
property lock_token
property locked_until
property partition_id
property partition_key
property scheduled_enqueue_time
property sequence_number
property session_id
property 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

property time_to_live
property user_properties

User defined properties on the message.

Return type

dict

property via_partition_key
class azure.servicebus.AutoLockRenew(executor=None, max_workers=None)[source]

Auto renew locks for messages and sessions using a background thread pool.

Parameters
  • executor (ThreadPoolExecutor) – A user-specified thread pool. This cannot be combined with setting max_workers.

  • max_workers (int) – Specifiy the maximum workers in the thread pool. If not specified the number used will be derived from the core count of the environment. This cannot be combined with executor.

Example: .. literalinclude:: ../samples/sync_samples/test_examples.py :start-after: [START auto_lock_renew_message] :end-before: [END auto_lock_renew_message] :language: python :dedent: 4 :caption: Automatically renew a message lock

Automatically renew a session lock
from azure.servicebus import AutoLockRenew

lock_renewal = AutoLockRenew(max_workers=4)
with session_client.get_receiver(session="MySessionID", idle_timeout=3) as session:
    # Auto renew session lock for 2 minutes
    lock_renewal.register(session, timeout=120)

    for message in session:
        process_message(message)
        message.complete()
register(renewable, timeout=300)[source]

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(wait=True)[source]

Shutdown the thread pool to clean up any remaining lock renewal threads.

Parameters

wait (bool) – Whether to block until thread pool has shutdown. Default is True.

class azure.servicebus.DeferredMessage(message, mode)[source]

A message that has been deferred.

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

abandon()[source]

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

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, reason=None)[source]

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 error description for dead-lettering the message.

  • reason (str) – The reason for dead-lettering the message. If reason is not set while description is set, then reason would be set the same as description.

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

A DeferredMessage cannot be deferred. Raises ValueError.

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 a threaded background task by registering the message with an azure.servicebus.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.MessageAlreadySettled is message has already been settled.

schedule(schedule_time)

Add a specific enqueue time to the message.

Parameters

schedule_time (datetime) – The scheduled time to enqueue the message.

property annotations

The annotations of the message.

Return type

dict

property body

The body of the Message.

Return type

bytes or generator[bytes]

property enqueue_sequence_number
property enqueued_time
property expired
property lock_token
property locked_until
property partition_id
property partition_key
property scheduled_enqueue_time
property sequence_number
property session_id
property 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

property time_to_live
property user_properties

User defined properties on the message.

Return type

dict

property via_partition_key
class azure.servicebus.ServiceBusClient(service_namespace=None, host_base='.servicebus.windows.net', shared_access_key_name=None, shared_access_key_value=None, transport_type=<TransportType.Amqp: 1>, http_request_timeout=65, http_request_session=None, debug=False)[source]

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 Public Azure.

  • shared_access_key_name (str) – SAS authentication key name.

  • shared_access_key_value (str) – SAS authentication key value.

  • transport_type (TransportType) – Optional. Underlying transport protocol type (Amqp or AmqpOverWebsocket) Default value is ~azure.servicebus.TransportType.Amqp

  • http_request_timeout (int) – Optional. Timeout for the HTTP request, in seconds. Default value is 65 seconds.

  • http_request_session (Session) – Optional. Session object to use for HTTP requests.

  • debug (bool) – Whether to output AMQP network trace to the logger.

create_queue(queue_name, lock_duration=30, max_size_in_megabytes=None, requires_duplicate_detection=False, requires_session=False, default_message_time_to_live=None, dead_lettering_on_message_expiration=False, duplicate_detection_history_time_window=None, max_delivery_count=None, enable_batched_operations=None)

Create a queue entity.

Parameters
  • queue_name (str) – The name of the new queue.

  • lock_duration (int) – The lock durection in seconds for each message in the queue.

  • max_size_in_megabytes (int) – The max size to allow the queue to grow to.

  • requires_duplicate_detection (bool) – Whether the queue will require every message with a specified time frame to have a unique ID. Non-unique messages will be discarded. Default value is False.

  • requires_session (bool) – Whether the queue will be sessionful, and therefore require all message to have a Session ID and be received by a sessionful receiver. Default value is False.

  • default_message_time_to_live (timedelta) – The length of time a message will remain in the queue before it is either discarded or moved to the dead letter queue.

  • dead_lettering_on_message_expiration (bool) – Whether to move expired messages to the dead letter queue. Default value is False.

  • duplicate_detection_history_time_window (timedelta) – The period within which all incoming messages must have a unique message ID.

  • max_delivery_count (int) – The maximum number of times a message will attempt to be delivered before it is moved to the dead letter queue.

  • enable_batched_operations

Type

enable_batched_operations: bool

Raises

~azure.servicebus.common.errors.ServiceBusConnectionError if the namespace is not found.

Raises

~azure.common.AzureConflictHttpError if a queue of the same name already exists.

create_subscription(topic_name, subscription_name, lock_duration=30, requires_session=None, default_message_time_to_live=None, dead_lettering_on_message_expiration=None, dead_lettering_on_filter_evaluation_exceptions=None, enable_batched_operations=None, max_delivery_count=None)

Create a subscription entity.

Parameters
  • topic_name – The name of the topic under which to create the subscription.

  • subscription_name (str) – The name of the new subscription.

  • lock_duration (int) – The lock durection in seconds for each message in the subscription.

  • requires_session (bool) – Whether the subscription will be sessionful, and therefore require all message to have a Session ID and be received by a sessionful receiver. Default value is False.

  • default_message_time_to_live (timedelta) – The length of time a message will remain in the subscription before it is either discarded or moved to the dead letter queue.

  • dead_lettering_on_message_expiration (bool) – Whether to move expired messages to the dead letter queue. Default value is False.

  • dead_lettering_on_filter_evaluation_exceptions (bool) – Whether to move messages that error on filtering into the dead letter queue. Default is False, and the messages will be discarded.

  • max_delivery_count (int) – The maximum number of times a message will attempt to be delivered before it is moved to the dead letter queue.

  • enable_batched_operations

Type

enable_batched_operations: bool

Raises

~azure.servicebus.common.errors.ServiceBusConnectionError if the namespace is not found.

Raises

~azure.common.AzureConflictHttpError if a queue of the same name already exists.

create_topic(topic_name, default_message_time_to_live=None, max_size_in_megabytes=None, requires_duplicate_detection=None, duplicate_detection_history_time_window=None, enable_batched_operations=None)

Create a topic entity.

Parameters
  • topic_name (str) – The name of the new topic.

  • max_size_in_megabytes (int) – The max size to allow the topic to grow to.

  • requires_duplicate_detection (bool) – Whether the topic will require every message with a specified time frame to have a unique ID. Non-unique messages will be discarded. Default value is False.

  • default_message_time_to_live (timedelta) – The length of time a message will remain in the topic before it is either discarded or moved to the dead letter queue.

  • duplicate_detection_history_time_window (timedelta) – The period within which all incoming messages must have a unique message ID.

  • enable_batched_operations

Type

enable_batched_operations: bool

Raises

~azure.servicebus.common.errors.ServiceBusConnectionError if the namespace is not found.

Raises

~azure.common.AzureConflictHttpError if a topic of the same name already exists.

delete_queue(queue_name, fail_not_exist=False)

Delete a queue entity.

Parameters
  • queue_name (str) – The name of the queue to delete.

  • fail_not_exist (bool) – Whether to raise an exception if the named queue is not found. If set to True, a ServiceBusResourceNotFound will be raised. Default value is False.

Raises

~azure.servicebus.common.errors.ServiceBusConnectionError if the namesapce is not found.

Raises

~azure.servicebus.common.errors.ServiceBusResourceNotFound if the queue is not found and fail_not_exist is set to True.

delete_subscription(topic_name, subscription_name, fail_not_exist=False)

Delete a subscription entity.

Parameters
  • topic_name (str) – The name of the topic where the subscription is.

  • subscription_name (str) – The name of the subscription to delete.

  • fail_not_exist (bool) – Whether to raise an exception if the named subscription or topic is not found. If set to True, a ServiceBusResourceNotFound will be raised. Default value is False.

Raises

~azure.servicebus.common.errors.ServiceBusConnectionError if the namesapce is not found.

Raises

~azure.servicebus.common.errors.ServiceBusResourceNotFound if the entity is not found and fail_not_exist is set to True.

delete_topic(topic_name, fail_not_exist=False)

Delete a topic entity.

Parameters
  • topic_name (str) – The name of the topic to delete.

  • fail_not_exist (bool) – Whether to raise an exception if the named topic is not found. If set to True, a ServiceBusResourceNotFound will be raised. Default value is False.

Raises

~azure.servicebus.common.errors.ServiceBusConnectionError if the namesapce is not found.

Raises

~azure.servicebus.common.errors.ServiceBusResourceNotFound if the topic is not found and fail_not_exist is set to True.

classmethod from_connection_string(conn_str, **kwargs)[source]

Create a Service Bus client from a connection string.

Parameters

conn_str (str) – The connection string.

get_queue(queue_name)[source]

Get a 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.

get_subscription(topic_name, subscription_name)[source]

Get a 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.

get_topic(topic_name)[source]

Get a 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.

list_queues()[source]

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

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

Get a 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.QueueClient(address, name, shared_access_key_name=None, shared_access_key_value=None, debug=False, **kwargs)[source]

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.

  • debug (bool) – Whether to output network trace logs to the logger. Default is False.

Construct a new Client to interact with the named Service Bus entity.

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 entity 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.

  • debug (bool) – Whether to output network trace logs to the logger. Default is False.

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

Create a Client from a Service Bus connection string.

Parameters
  • conn_str (str) – The connection string.

  • name – The name of the entity, if the ‘EntityName’ property is not included in the connection string.

classmethod from_entity(address, entity, **kwargs)
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 queue.

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

get_properties()

Perform an operation to update the properties of the entity.

Returns

The properties of the entity as a dictionary.

Return type

dict[str, Any]

Raises

~azure.servicebus.common.errors.ServiceBusResourceNotFound if the entity does not exist.

Raises

~azure.servicebus.common.errors.ServiceBusConnectionError if the endpoint cannot be reached.

Raises

~azure.common.AzureHTTPError if the credentials are invalid.

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 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

Raises

If the current Service Bus entity requires sessions, a TypeError will be raised.

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

Get a Sender for the Service Bus endpoint.

A Sender represents a single open Connection with 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

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

List session IDs.

List the Session IDs with pending messages in the queue 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.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]

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

Receive messages by sequence number that have been previously 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[Message]

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: .. literalinclude:: ../samples/sync_samples/test_examples.py :start-after: [START send_message_service_bus] :end-before: [END send_message_service_bus] :language: python :dedent: 4 :caption: Send a message to current entity via a single use connection

Send messages to current entity via a single use connection
from azure.servicebus import Message

message1 = Message("Hello World!")
message2 = Message("How are you?")
queue_client.send([message1, message2])
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.

class azure.servicebus.TopicClient(address, name, shared_access_key_name=None, shared_access_key_value=None, debug=False, **kwargs)[source]

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.

  • debug (bool) – Whether to output network trace logs to the logger. Default is False.

Construct a new Client to interact with the named Service Bus entity.

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 entity 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.

  • debug (bool) – Whether to output network trace logs to the logger. Default is False.

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

Create a Client from a Service Bus connection string.

Parameters
  • conn_str (str) – The connection string.

  • name – The name of the entity, if the ‘EntityName’ property is not included in the connection string.

classmethod from_entity(address, entity, **kwargs)
get_properties()

Perform an operation to update the properties of the entity.

Returns

The properties of the entity as a dictionary.

Return type

dict[str, Any]

Raises

~azure.servicebus.common.errors.ServiceBusResourceNotFound if the entity does not exist.

Raises

~azure.servicebus.common.errors.ServiceBusConnectionError if the endpoint cannot be reached.

Raises

~azure.common.AzureHTTPError if the credentials are invalid.

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

Get a Sender for the Service Bus endpoint.

A Sender represents a single open Connection with 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

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: .. literalinclude:: ../samples/sync_samples/test_examples.py :start-after: [START send_message_service_bus] :end-before: [END send_message_service_bus] :language: python :dedent: 4 :caption: Send a message to current entity via a single use connection

Send messages to current entity via a single use connection
from azure.servicebus import Message

message1 = Message("Hello World!")
message2 = Message("How are you?")
queue_client.send([message1, message2])
class azure.servicebus.SubscriptionClient(address, name, shared_access_key_name=None, shared_access_key_value=None, debug=False, **kwargs)[source]

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.

  • debug (bool) – Whether to output network trace logs to the logger. Default is False.

classmethod from_connection_string(conn_str, name, topic=None, **kwargs)[source]

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

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

get_properties()

Perform an operation to update the properties of the entity.

Returns

The properties of the entity as a dictionary.

Return type

dict[str, Any]

Raises

~azure.servicebus.common.errors.ServiceBusResourceNotFound if the entity does not exist.

Raises

~azure.servicebus.common.errors.ServiceBusConnectionError if the endpoint cannot be reached.

Raises

~azure.common.AzureHTTPError if the credentials are invalid.

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 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

Raises

If the current Service Bus entity requires sessions, a TypeError will be raised.

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

List session IDs.

List the Session IDs with pending messages in the queue 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.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]

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

Receive messages by sequence number that have been previously 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[Message]

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.

class azure.servicebus.ReceiveSettleMode[source]

An enumeration.

PeekLock = <ReceiverSettleMode.PeekLock: 1>
ReceiveAndDelete = <ReceiverSettleMode.ReceiveAndDelete: 0>
class azure.servicebus.TransportType[source]

Transport type The underlying transport protocol type:

Amqp: AMQP over the default TCP transport protocol, it uses port 5671. AmqpOverWebsocket: Amqp over the Web Sockets transport protocol, it uses port 443.

Amqp = 1
AmqpOverWebsocket = 2

Submodules

azure.servicebus.base_handler module

class azure.servicebus.base_handler.BaseHandler(endpoint, auth_config, connection=None, encoding='UTF-8', debug=False, **kwargs)[source]
close(exception=None)[source]

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.

open()[source]

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.

reconnect()[source]

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.receive_handler module

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

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.

  • 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.

close(exception=None)[source]

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.

fetch_next(max_batch_size=None, timeout=None)[source]

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]

next()[source]
open()[source]

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

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]

receive_deferred_messages(sequence_numbers, mode=<ReceiveSettleMode.PeekLock: <ReceiverSettleMode.PeekLock: 1>>)[source]

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]

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.

property queue_size

The current size of the unprocessed message queue.

Return type

int

property receiver_shutdown
class azure.servicebus.receive_handler.SessionReceiver(handler_id, source, auth_config, session=None, connection=None, encoding='UTF-8', debug=False, **kwargs)[source]

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: .. literalinclude:: ../samples/sync_samples/test_examples.py :start-after: [START create_session_receiver_client] :end-before: [END create_session_receiver_client] :language: python :dedent: 4 :caption: Running a session receiver within a context manager.

Running a session receiver for the next available session.
from azure.servicebus import NEXT_AVAILABLE, NoActiveSession

try:
    with session_client.get_receiver(session=NEXT_AVAILABLE, idle_timeout=5) as receiver:
        for message in receiver:
            process_message(message)
except NoActiveSession:
    pass
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.

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]

get_session_state()[source]

Get the session state.

Returns None if no state has been set.

Return type

str

list_sessions(updated_since=None, max_results=100, skip=0)[source]

List session IDs.

List the Session IDs with pending messages in the queue 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.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]

next()
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=None)[source]

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]

receive_deferred_messages(sequence_numbers, mode=<ReceiveSettleMode.PeekLock: <ReceiverSettleMode.PeekLock: 1>>)[source]

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]

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.

renew_lock()[source]

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 a threaded background task by registering the session with an azure.servicebus.AutoLockRenew instance.

set_session_state(state)[source]

Set the session state.

Parameters

state (str, bytes or bytearray) – The state value.

property expired

Whether the receivers lock on a particular session has expired.

Return type

bool

property queue_size

The current size of the unprocessed message queue.

Return type

int

property receiver_shutdown

azure.servicebus.send_handler module

class azure.servicebus.send_handler.Sender(handler_id, target, auth_config, session=None, connection=None, encoding='UTF-8', debug=False, **kwargs)[source]

A message sender.

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

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

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.

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.

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.

queue_message(message)

Queue a message to be sent later.

This operation should be followed up with send_pending_messages.

Parameters

message (Message) – The message to be sent.

reconnect()[source]

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

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]

send(message)[source]

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.

send_pending_messages()[source]

Wait until all transferred events 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]]

class azure.servicebus.send_handler.SessionSender(handler_id, target, auth_config, session=None, connection=None, encoding='UTF-8', debug=False, **kwargs)[source]

A session message 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).

  • 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.

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.

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.

queue_message(message)[source]

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.

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

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]

send(message)[source]

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.

Raises

ValueError if there is no session ID specified.

send_pending_messages()

Wait until all transferred events 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]]

azure.servicebus.servicebus_client module

class azure.servicebus.servicebus_client.QueueClient(address, name, shared_access_key_name=None, shared_access_key_value=None, debug=False, **kwargs)[source]

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.

  • debug (bool) – Whether to output network trace logs to the logger. Default is False.

Construct a new Client to interact with the named Service Bus entity.

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 entity 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.

  • debug (bool) – Whether to output network trace logs to the logger. Default is False.

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

Create a Client from a Service Bus connection string.

Parameters
  • conn_str (str) – The connection string.

  • name – The name of the entity, if the ‘EntityName’ property is not included in the connection string.

classmethod from_entity(address, entity, **kwargs)
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 queue.

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

get_properties()

Perform an operation to update the properties of the entity.

Returns

The properties of the entity as a dictionary.

Return type

dict[str, Any]

Raises

~azure.servicebus.common.errors.ServiceBusResourceNotFound if the entity does not exist.

Raises

~azure.servicebus.common.errors.ServiceBusConnectionError if the endpoint cannot be reached.

Raises

~azure.common.AzureHTTPError if the credentials are invalid.

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 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

Raises

If the current Service Bus entity requires sessions, a TypeError will be raised.

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

Get a Sender for the Service Bus endpoint.

A Sender represents a single open Connection with 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

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

List session IDs.

List the Session IDs with pending messages in the queue 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.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]

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

Receive messages by sequence number that have been previously 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[Message]

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: .. literalinclude:: ../samples/sync_samples/test_examples.py :start-after: [START send_message_service_bus] :end-before: [END send_message_service_bus] :language: python :dedent: 4 :caption: Send a message to current entity via a single use connection

Send messages to current entity via a single use connection
from azure.servicebus import Message

message1 = Message("Hello World!")
message2 = Message("How are you?")
queue_client.send([message1, message2])
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.

class azure.servicebus.servicebus_client.ReceiveClientMixin[source]
get_deadletter_receiver(transfer_deadletter=False, prefetch=0, mode=<ReceiveSettleMode.PeekLock: <ReceiverSettleMode.PeekLock: 1>>, idle_timeout=0, **kwargs)[source]

Get a Receiver for the deadletter endpoint of the queue.

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

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

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 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

Raises

If the current Service Bus entity requires sessions, a TypeError will be raised.

list_sessions(updated_since=None, max_results=100, skip=0, **kwargs)[source]

List session IDs.

List the Session IDs with pending messages in the queue 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.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)[source]

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]

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

Receive messages by sequence number that have been previously 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[Message]

settle_deferred_messages(settlement, messages, **kwargs)[source]

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.

class azure.servicebus.servicebus_client.SendClientMixin[source]
get_sender(message_timeout=0, session=None, **kwargs)[source]

Get a Sender for the Service Bus endpoint.

A Sender represents a single open Connection with 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

send(messages, message_timeout=0, session=None, **kwargs)[source]

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: .. literalinclude:: ../samples/sync_samples/test_examples.py :start-after: [START send_message_service_bus] :end-before: [END send_message_service_bus] :language: python :dedent: 4 :caption: Send a message to current entity via a single use connection

Send messages to current entity via a single use connection
from azure.servicebus import Message

message1 = Message("Hello World!")
message2 = Message("How are you?")
queue_client.send([message1, message2])
class azure.servicebus.servicebus_client.ServiceBusClient(service_namespace=None, host_base='.servicebus.windows.net', shared_access_key_name=None, shared_access_key_value=None, transport_type=<TransportType.Amqp: 1>, http_request_timeout=65, http_request_session=None, debug=False)[source]

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 Public Azure.

  • shared_access_key_name (str) – SAS authentication key name.

  • shared_access_key_value (str) – SAS authentication key value.

  • transport_type (TransportType) – Optional. Underlying transport protocol type (Amqp or AmqpOverWebsocket) Default value is ~azure.servicebus.TransportType.Amqp

  • http_request_timeout (int) – Optional. Timeout for the HTTP request, in seconds. Default value is 65 seconds.

  • http_request_session (Session) – Optional. Session object to use for HTTP requests.

  • debug (bool) – Whether to output AMQP network trace to the logger.

create_queue(queue_name, lock_duration=30, max_size_in_megabytes=None, requires_duplicate_detection=False, requires_session=False, default_message_time_to_live=None, dead_lettering_on_message_expiration=False, duplicate_detection_history_time_window=None, max_delivery_count=None, enable_batched_operations=None)

Create a queue entity.

Parameters
  • queue_name (str) – The name of the new queue.

  • lock_duration (int) – The lock durection in seconds for each message in the queue.

  • max_size_in_megabytes (int) – The max size to allow the queue to grow to.

  • requires_duplicate_detection (bool) – Whether the queue will require every message with a specified time frame to have a unique ID. Non-unique messages will be discarded. Default value is False.

  • requires_session (bool) – Whether the queue will be sessionful, and therefore require all message to have a Session ID and be received by a sessionful receiver. Default value is False.

  • default_message_time_to_live (timedelta) – The length of time a message will remain in the queue before it is either discarded or moved to the dead letter queue.

  • dead_lettering_on_message_expiration (bool) – Whether to move expired messages to the dead letter queue. Default value is False.

  • duplicate_detection_history_time_window (timedelta) – The period within which all incoming messages must have a unique message ID.

  • max_delivery_count (int) – The maximum number of times a message will attempt to be delivered before it is moved to the dead letter queue.

  • enable_batched_operations

Type

enable_batched_operations: bool

Raises

~azure.servicebus.common.errors.ServiceBusConnectionError if the namespace is not found.

Raises

~azure.common.AzureConflictHttpError if a queue of the same name already exists.

create_subscription(topic_name, subscription_name, lock_duration=30, requires_session=None, default_message_time_to_live=None, dead_lettering_on_message_expiration=None, dead_lettering_on_filter_evaluation_exceptions=None, enable_batched_operations=None, max_delivery_count=None)

Create a subscription entity.

Parameters
  • topic_name – The name of the topic under which to create the subscription.

  • subscription_name (str) – The name of the new subscription.

  • lock_duration (int) – The lock durection in seconds for each message in the subscription.

  • requires_session (bool) – Whether the subscription will be sessionful, and therefore require all message to have a Session ID and be received by a sessionful receiver. Default value is False.

  • default_message_time_to_live (timedelta) – The length of time a message will remain in the subscription before it is either discarded or moved to the dead letter queue.

  • dead_lettering_on_message_expiration (bool) – Whether to move expired messages to the dead letter queue. Default value is False.

  • dead_lettering_on_filter_evaluation_exceptions (bool) – Whether to move messages that error on filtering into the dead letter queue. Default is False, and the messages will be discarded.

  • max_delivery_count (int) – The maximum number of times a message will attempt to be delivered before it is moved to the dead letter queue.

  • enable_batched_operations

Type

enable_batched_operations: bool

Raises

~azure.servicebus.common.errors.ServiceBusConnectionError if the namespace is not found.

Raises

~azure.common.AzureConflictHttpError if a queue of the same name already exists.

create_topic(topic_name, default_message_time_to_live=None, max_size_in_megabytes=None, requires_duplicate_detection=None, duplicate_detection_history_time_window=None, enable_batched_operations=None)

Create a topic entity.

Parameters
  • topic_name (str) – The name of the new topic.

  • max_size_in_megabytes (int) – The max size to allow the topic to grow to.

  • requires_duplicate_detection (bool) – Whether the topic will require every message with a specified time frame to have a unique ID. Non-unique messages will be discarded. Default value is False.

  • default_message_time_to_live (timedelta) – The length of time a message will remain in the topic before it is either discarded or moved to the dead letter queue.

  • duplicate_detection_history_time_window (timedelta) – The period within which all incoming messages must have a unique message ID.

  • enable_batched_operations

Type

enable_batched_operations: bool

Raises

~azure.servicebus.common.errors.ServiceBusConnectionError if the namespace is not found.

Raises

~azure.common.AzureConflictHttpError if a topic of the same name already exists.

delete_queue(queue_name, fail_not_exist=False)

Delete a queue entity.

Parameters
  • queue_name (str) – The name of the queue to delete.

  • fail_not_exist (bool) – Whether to raise an exception if the named queue is not found. If set to True, a ServiceBusResourceNotFound will be raised. Default value is False.

Raises

~azure.servicebus.common.errors.ServiceBusConnectionError if the namesapce is not found.

Raises

~azure.servicebus.common.errors.ServiceBusResourceNotFound if the queue is not found and fail_not_exist is set to True.

delete_subscription(topic_name, subscription_name, fail_not_exist=False)

Delete a subscription entity.

Parameters
  • topic_name (str) – The name of the topic where the subscription is.

  • subscription_name (str) – The name of the subscription to delete.

  • fail_not_exist (bool) – Whether to raise an exception if the named subscription or topic is not found. If set to True, a ServiceBusResourceNotFound will be raised. Default value is False.

Raises

~azure.servicebus.common.errors.ServiceBusConnectionError if the namesapce is not found.

Raises

~azure.servicebus.common.errors.ServiceBusResourceNotFound if the entity is not found and fail_not_exist is set to True.

delete_topic(topic_name, fail_not_exist=False)

Delete a topic entity.

Parameters
  • topic_name (str) – The name of the topic to delete.

  • fail_not_exist (bool) – Whether to raise an exception if the named topic is not found. If set to True, a ServiceBusResourceNotFound will be raised. Default value is False.

Raises

~azure.servicebus.common.errors.ServiceBusConnectionError if the namesapce is not found.

Raises

~azure.servicebus.common.errors.ServiceBusResourceNotFound if the topic is not found and fail_not_exist is set to True.

classmethod from_connection_string(conn_str, **kwargs)[source]

Create a Service Bus client from a connection string.

Parameters

conn_str (str) – The connection string.

get_queue(queue_name)[source]

Get a 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.

get_subscription(topic_name, subscription_name)[source]

Get a 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.

get_topic(topic_name)[source]

Get a 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.

list_queues()[source]

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

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

Get a 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.servicebus_client.SubscriptionClient(address, name, shared_access_key_name=None, shared_access_key_value=None, debug=False, **kwargs)[source]

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.

  • debug (bool) – Whether to output network trace logs to the logger. Default is False.

classmethod from_connection_string(conn_str, name, topic=None, **kwargs)[source]

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

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

get_properties()

Perform an operation to update the properties of the entity.

Returns

The properties of the entity as a dictionary.

Return type

dict[str, Any]

Raises

~azure.servicebus.common.errors.ServiceBusResourceNotFound if the entity does not exist.

Raises

~azure.servicebus.common.errors.ServiceBusConnectionError if the endpoint cannot be reached.

Raises

~azure.common.AzureHTTPError if the credentials are invalid.

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 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

Raises

If the current Service Bus entity requires sessions, a TypeError will be raised.

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

List session IDs.

List the Session IDs with pending messages in the queue 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.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]

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

Receive messages by sequence number that have been previously 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[Message]

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.

class azure.servicebus.servicebus_client.TopicClient(address, name, shared_access_key_name=None, shared_access_key_value=None, debug=False, **kwargs)[source]

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.

  • debug (bool) – Whether to output network trace logs to the logger. Default is False.

Construct a new Client to interact with the named Service Bus entity.

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 entity 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.

  • debug (bool) – Whether to output network trace logs to the logger. Default is False.

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

Create a Client from a Service Bus connection string.

Parameters
  • conn_str (str) – The connection string.

  • name – The name of the entity, if the ‘EntityName’ property is not included in the connection string.

classmethod from_entity(address, entity, **kwargs)
get_properties()

Perform an operation to update the properties of the entity.

Returns

The properties of the entity as a dictionary.

Return type

dict[str, Any]

Raises

~azure.servicebus.common.errors.ServiceBusResourceNotFound if the entity does not exist.

Raises

~azure.servicebus.common.errors.ServiceBusConnectionError if the endpoint cannot be reached.

Raises

~azure.common.AzureHTTPError if the credentials are invalid.

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

Get a Sender for the Service Bus endpoint.

A Sender represents a single open Connection with 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

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: .. literalinclude:: ../samples/sync_samples/test_examples.py :start-after: [START send_message_service_bus] :end-before: [END send_message_service_bus] :language: python :dedent: 4 :caption: Send a message to current entity via a single use connection

Send messages to current entity via a single use connection
from azure.servicebus import Message

message1 = Message("Hello World!")
message2 = Message("How are you?")
queue_client.send([message1, message2])