azure.servicebus package

Submodules

azure.servicebus.base_handler module

azure.servicebus.receive_handler module

azure.servicebus.send_handler module

azure.servicebus.servicebus_client module

Module contents

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

Bases: azure.servicebus.exceptions.ServiceBusError

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

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

Bases: azure.servicebus.exceptions.ServiceBusError

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

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

Bases: azure.servicebus.exceptions.ServiceBusError

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

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

Bases: azure.servicebus.exceptions.ServiceBusError

Failed to settle the message.

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

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

Bases: azure.servicebus.exceptions.ServiceBusError

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

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

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

Bases: azure.servicebus.exceptions.ServiceBusError

A message failed to send to the Service Bus entity.

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

Bases: azure.servicebus.exceptions.ServiceBusError

Attempt to settle a message failed.

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

Bases: azure.servicebus.exceptions.ServiceBusError

No active Sessions are available to receive from.

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

Bases: azure.servicebus.exceptions.ServiceBusError

An error occured when authorizing the connection.

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

Bases: azure.servicebus.exceptions.ServiceBusError

An error occured in the connection.

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

Bases: Exception

An error occured.

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

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

Bases: azure.servicebus.exceptions.ServiceBusError

The Service Bus entity could not be reached.

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

Bases: azure.servicebus.exceptions.ServiceBusError

The lock on the session has expired.

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

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

Bases: object

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) – Specify 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:

register(renewable, timeout=300)[source]

Register a renewable entity for automatic lock renewal.

Parameters
  • renewable (ReceivedMessage or Session) – A locked entity that needs to be renewed.

  • timeout (float) – 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.BatchMessage(max_size_in_bytes: Optional[int] = None)[source]

Bases: object

A batch of messages.

Sending messages in a batch is more performant than sending individual message. BatchMessage helps you create the maximum allowed size batch of Message to improve sending performance.

Use the add method to add messages until the maximum batch size limit in bytes has been reached - at which point a ValueError will be raised.

Please use the create_batch method of ServiceBusSender to create a BatchMessage object instead of instantiating a BatchMessage object directly.

Variables
  • max_size_in_bytes (int) – The maximum size of bytes data that a BatchMessage object can hold.

  • message (BatchMessage) – Internal AMQP BatchMessage object.

Parameters

max_size_in_bytes (int) – The maximum size of bytes data that a BatchMessage object can hold.

add(message: azure.servicebus._common.message.Message) → None[source]

Try to add a single Message to the batch.

The total size of an added message is the sum of its body, properties, etc. If this added size results in the batch exceeding the maximum batch size, a ValueError will be raised.

Parameters

message (Message) – The Message to be added to the batch.

Return type

None

Raises

ValueError, when exceeding the size limit.

property size_in_bytes

The combined size of the events in the batch, in bytes.

Return type

int

class azure.servicebus.Message(body, **kwargs)[source]

Bases: object

A Service Bus Message.

Variables
  • properties (MessageProperties) – Properties of the internal AMQP message object.

  • header (MessageHeader) – Header of the internal AMQP message object.

  • message (Message) – Internal AMQP message object.

Parameters

body (str or bytes) – The data to send in a single message.

Keyword Arguments
  • encoding (str) – The encoding for string data. Default is UTF-8.

  • session_id (str) – An optional session ID for the message to be sent.

Example:

schedule(schedule_time_utc: datetime.datetime) → None[source]

Add a specific utc enqueue time to the message.

Parameters

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

Return type

None

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

int

Type

rtype

property partition_key

str

Type

rtype

property session_id

The session id of the message

Return type

str

property time_to_live

~datetime.timedelta

Type

rtype

property user_properties

User defined properties on the message.

Return type

dict

property via_partition_key

str

Type

rtype

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

Bases: azure.servicebus._common.message.Message

A preview message.

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

Variables

received_timestamp_utc (datetime.datetime) – The utc timestamp of when the message is received.

property enqueued_time_utc

~datetime.datetime

Type

rtype

property partition_id

int

Type

rtype

property scheduled_enqueue_time_utc

~datetime.datetime

Type

rtype

property sequence_number

int

Type

rtype

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

class azure.servicebus.ReceiveSettleMode(value)[source]

Bases: enum.Enum

An enumeration.

PeekLock = <ReceiverSettleMode.PeekLock: 1>
ReceiveAndDelete = <ReceiverSettleMode.ReceiveAndDelete: 0>
class azure.servicebus.ReceivedMessage(message, mode=<ReceiveSettleMode.PeekLock: <ReceiverSettleMode.PeekLock: 1>>)[source]

Bases: azure.servicebus._common.message.PeekMessage

A Service Bus Message received from service side.

Variables

auto_renew_error (AutoLockRenewTimeout or AutoLockRenewFailed) – Error when AutoLockRenew is used and it fails to renew the message lock.

Example:

abandon() → None[source]

Abandon the message.

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

Return type

None

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

Complete the message.

This removes the message from the queue.

Return type

None

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(reason: Optional[str] = None, description: Optional[str] = None) → 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.

Parameters
  • reason (str) – The reason for dead-lettering the message.

  • description (str) – The detailed description for dead-lettering the message.

Return type

None

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() → None[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.

Return type

None

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() → None[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.

Return type

None

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.

property expired

bool

Type

rtype

property lock_token

~uuid.UUID or str

Type

rtype

property locked_until_utc

datetime.datetime

Type

rtype

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

class azure.servicebus.ServiceBusClient(fully_qualified_namespace: str, credential: TokenCredential, **kwargs: Any)[source]

Bases: object

The ServiceBusClient class defines a high level interface for getting ServiceBusSender and ServiceBusReceiver.

Variables

fully_qualified_namespace (str) – The fully qualified host name for the Service Bus namespace. The namespace format is: <yournamespace>.servicebus.windows.net.

Parameters
  • fully_qualified_namespace (str) – The fully qualified host name for the Service Bus namespace. The namespace format is: <yournamespace>.servicebus.windows.net.

  • credential (TokenCredential) – The credential object used for authentication which implements a particular interface for getting tokens. It accepts ServiceBusSharedKeyCredential, or credential objects generated by the azure-identity library and objects that implement the get_token(self, *scopes) method.

Keyword Arguments
  • entity_name (str) – Optional entity name, this can be the name of Queue or Topic. It must be specified if the credential is for specific Queue or Topic.

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

  • transport_type (TransportType) – The type of transport protocol that will be used for communicating with the Service Bus service. Default is TransportType.Amqp.

  • http_proxy (dict) – HTTP proxy settings. This must be a dictionary with the following keys: ‘proxy_hostname’ (str value) and ‘proxy_port’ (int value). Additionally the following keys may also be present: ‘username’, ‘password’.

Example:

close() → None[source]

Close down the ServiceBus client and the underlying connection.

Returns

None

classmethod from_connection_string(conn_str: str, **kwargs: Any) → azure.servicebus._servicebus_client.ServiceBusClient[source]

Create a ServiceBusClient from a connection string.

Parameters

conn_str (str) – The connection string of a Service Bus.

Keyword Arguments
  • entity_name (str) – Optional entity name, this can be the name of Queue or Topic. It must be specified if the credential is for specific Queue or Topic.

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

  • transport_type (TransportType) – The type of transport protocol that will be used for communicating with the Service Bus service. Default is TransportType.Amqp.

  • http_proxy (dict) – HTTP proxy settings. This must be a dictionary with the following keys: ‘proxy_hostname’ (str value) and ‘proxy_port’ (int value). Additionally the following keys may also be present: ‘username’, ‘password’.

Return type

ServiceBusClient

Example:

get_queue_receiver(queue_name: str, **kwargs: Any) → azure.servicebus._servicebus_receiver.ServiceBusReceiver[source]

Get ServiceBusReceiver for the specific queue.

Parameters
  • queue_name (str) – The path of specific Service Bus Queue the client connects to.

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

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

  • session_id (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 messages from 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.

  • idle_timeout (float) – The timeout in seconds between received messages after which the receiver will automatically shutdown. The default value is 0, meaning no timeout.

  • retry_total (int) – The total number of attempts to redo a failed operation when an error occurs. Default value is 3.

Return type

ServiceBusReceiver

Raises

ServiceBusConnectionError ServiceBusAuthorizationError

Example:

get_queue_sender(queue_name: str, **kwargs: Any) → azure.servicebus._servicebus_sender.ServiceBusSender[source]

Get ServiceBusSender for the specific queue.

Parameters

queue_name (str) – The path of specific Service Bus Queue the client connects to.

Keyword Arguments

retry_total (int) – The total number of attempts to redo a failed operation when an error occurs. Default value is 3.

Return type

ServiceBusSender

Raises

ServiceBusConnectionError ServiceBusAuthorizationError

Example:

class azure.servicebus.ServiceBusReceiver(fully_qualified_namespace: str, credential: TokenCredential, **kwargs: Any)[source]

Bases: azure.servicebus._base_handler.BaseHandler, azure.servicebus._servicebus_receiver.ReceiverMixin

The ServiceBusReceiver class defines a high level interface for receiving messages from the Azure Service Bus Queue or Topic Subscription.

Variables
  • fully_qualified_namespace (str) – The fully qualified host name for the Service Bus namespace. The namespace format is: <yournamespace>.servicebus.windows.net.

  • entity_path (str) – The path of the entity that the client connects to.

Parameters
  • fully_qualified_namespace (str) – The fully qualified host name for the Service Bus namespace. The namespace format is: <yournamespace>.servicebus.windows.net.

  • credential (TokenCredential) – The credential object used for authentication which implements a particular interface for getting tokens. It accepts ServiceBusSharedKeyCredential, or credential objects generated by the azure-identity library and objects that implement the get_token(self, *scopes) method.

Keyword Arguments
  • queue_name (str) – The path of specific Service Bus Queue the client connects to.

  • topic_name (str) – The path of specific Service Bus Topic which contains the Subscription the client connects to.

  • subscription_name (str) – The path of specific Service Bus Subscription under the specified Topic the client connects to.

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

  • idle_timeout (float) – The timeout in seconds between received messages after which the receiver will automatically shutdown. The default value is 0, meaning no timeout.

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

  • session_id (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 messages from the next available session, set this to NEXT_AVAILABLE.

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

  • retry_total (int) – The total number of attempts to redo a failed operation when an error occurs. Default value is 3.

  • transport_type (TransportType) – The type of transport protocol that will be used for communicating with the Service Bus service. Default is TransportType.Amqp.

  • http_proxy (dict) – HTTP proxy settings. This must be a dictionary with the following keys: ‘proxy_hostname’ (str value) and ‘proxy_port’ (int value). Additionally the following keys may also be present: ‘username’, ‘password’.

Example:

classmethod from_connection_string(conn_str: str, **kwargs: Any) → azure.servicebus._servicebus_receiver.ServiceBusReceiver[source]

Create a ServiceBusReceiver from a connection string.

Parameters

conn_str – The connection string of a Service Bus.

Keyword Arguments
  • queue_name (str) – The path of specific Service Bus Queue the client connects to.

  • topic_name (str) – The path of specific Service Bus Topic which contains the Subscription the client connects to.

  • subscription_name (str) – The path of specific Service Bus Subscription under the specified Topic the client connects to.

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

  • session_id (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 messages from 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.

  • idle_timeout (float) – The timeout in seconds between received messages after which the receiver will automatically shutdown. The default value is 0, meaning no timeout.

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

  • retry_total (int) – The total number of attempts to redo a failed operation when an error occurs. Default value is 3.

  • transport_type (TransportType) – The type of transport protocol that will be used for communicating with the Service Bus service. Default is TransportType.Amqp.

  • http_proxy (dict) – HTTP proxy settings. This must be a dictionary with the following keys: ‘proxy_hostname’ (str value) and ‘proxy_port’ (int value). Additionally the following keys may also be present: ‘username’, ‘password’.

Return type

ServiceBusReceiverClient

Example:

next()
peek(message_count: int = 1, sequence_number: Optional[int] = None) → List[azure.servicebus._common.message.PeekMessage][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
  • message_count (int) – The maximum number of messages to try and peek. The default value is 1.

  • sequence_number (int) – A message sequence number from which to start browsing messages.

Return type

list[PeekMessage]

Example:

receive(max_batch_size: Optional[int] = None, max_wait_time: Optional[float] = None) → List[azure.servicebus._common.message.ReceivedMessage][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.

  • max_wait_time (float) – Maximum time to wait in seconds for the first message to arrive. If no messages arrive, and no timeout is specified, this call will not return until the connection is closed. If specified, an no messages arrive within the timeout period, an empty list will be returned.

Return type

list[Message]

Example:

receive_deferred_messages(sequence_numbers: List[int]) → List[azure.servicebus._common.message.ReceivedMessage][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.

Return type

list[ReceivedMessage]

Example:

property session

Get the ServiceBusSession object linked with the receiver. Session is only available to session-enabled entities.

Return type

ServiceBusSession

Raises

TypeError

Example:

class azure.servicebus.ServiceBusSender(fully_qualified_namespace: str, credential: TokenCredential, **kwargs: Any)[source]

Bases: azure.servicebus._base_handler.BaseHandler, azure.servicebus._servicebus_sender.SenderMixin

The ServiceBusSender class defines a high level interface for sending messages to the Azure Service Bus Queue or Topic.

Variables
  • fully_qualified_namespace (str) – The fully qualified host name for the Service Bus namespace. The namespace format is: <yournamespace>.servicebus.windows.net.

  • entity_name (str) – The name of the entity that the client connects to.

Parameters
  • fully_qualified_namespace (str) – The fully qualified host name for the Service Bus namespace. The namespace format is: <yournamespace>.servicebus.windows.net.

  • credential (TokenCredential) – The credential object used for authentication which implements a particular interface for getting tokens. It accepts ServiceBusSharedKeyCredential, or credential objects generated by the azure-identity library and objects that implement the get_token(self, *scopes) method.

Keyword Arguments
  • queue_name (str) – The path of specific Service Bus Queue the client connects to.

  • topic_name (str) – The path of specific Service Bus Topic the client connects to.

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

  • retry_total (int) – The total number of attempts to redo a failed operation when an error occurs. Default value is 3.

  • transport_type (TransportType) – The type of transport protocol that will be used for communicating with the Service Bus service. Default is TransportType.Amqp.

  • http_proxy (dict) – HTTP proxy settings. This must be a dictionary with the following keys: ‘proxy_hostname’ (str value) and ‘proxy_port’ (int value). Additionally the following keys may also be present: ‘username’, ‘password’.

Example:

create_batch(max_size_in_bytes: Optional[int] = None) → azure.servicebus._common.message.BatchMessage[source]

Create a BatchMessage object with the max size of all content being constrained by max_size_in_bytes. The max_size should be no greater than the max allowed message size defined by the service.

Parameters

max_size_in_bytes (int) – The maximum size of bytes data that a BatchMessage object can hold. By default, the value is determined by your Service Bus tier.

Return type

BatchMessage

Example:

classmethod from_connection_string(conn_str: str, **kwargs: Any) → azure.servicebus._servicebus_sender.ServiceBusSender[source]

Create a ServiceBusSender from a connection string.

Parameters

conn_str – The connection string of a Service Bus.

Keyword Arguments
  • queue_name (str) – The path of specific Service Bus Queue the client connects to. Only one of queue_name or topic_name can be provided.

  • topic_name (str) – The path of specific Service Bus Topic the client connects to. Only one of queue_name or topic_name can be provided.

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

  • retry_total (int) – The total number of attempts to redo a failed operation when an error occurs. Default value is 3.

  • transport_type (TransportType) – The type of transport protocol that will be used for communicating with the Service Bus service. Default is TransportType.Amqp.

  • http_proxy (dict) – HTTP proxy settings. This must be a dictionary with the following keys: ‘proxy_hostname’ (str value) and ‘proxy_port’ (int value). Additionally the following keys may also be present: ‘username’, ‘password’.

Return type

ServiceBusSenderClient

Example:

send(message: Union[azure.servicebus._common.message.Message, azure.servicebus._common.message.BatchMessage], timeout: Optional[float] = None) → None[source]

Sends message and blocks until acknowledgement is received or operation times out.

Parameters
  • message (Message) – The ServiceBus message to be sent.

  • timeout (float) – The maximum wait time to send the event data.

Return type

None

Raises

~azure.servicebus.common.errors.MessageSendFailed if the message fails to send or ~azure.servicebus.common.errors.OperationTimeoutError if sending times out.

Example:

class azure.servicebus.ServiceBusSession(session_id, receiver, encoding='UTF-8')[source]

Bases: object

The ServiceBusSession is used for manage session states and lock renewal.

Please use the instance variable `session` on the ServiceBusReceiver to get the corresponding ServiceBusSession object linked with the receiver instead of instantiating a ServiceBusSession object directly.

Variables

auto_renew_error (AutoLockRenewTimeout or AutoLockRenewFailed) – Error when AutoLockRenew is used and it fails to renew the session lock.

Example:

get_session_state() → str[source]

Get the session state.

Returns None if no state has been set.

Return type

str

Example:

renew_lock() → None[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.

Example:

set_session_state(state: Union[str, bytes, bytearray]) → None[source]

Set the session state.

Parameters

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

Example:

property expired

Whether the receivers lock on a particular session has expired.

Return type

bool

property locked_until_utc

The time at which this session’s lock will expire.

Return type

datetime.datetime

property session_id

Session id of the current session.

Return type

str

class azure.servicebus.ServiceBusSharedKeyCredential(policy: str, key: str)[source]

Bases: object

The shared access key credential used for authentication.

Parameters
  • policy (str) – The name of the shared access policy.

  • key (str) – The shared access key.

get_token(*scopes: str, **kwargs: Any) → azure.servicebus._base_handler.AccessToken[source]
class azure.servicebus.TransportType(value)[source]

Bases: enum.Enum

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