azure.servicebus package

class azure.servicebus.AutoLockRenewer(max_lock_renewal_duration: float = 300, on_lock_renew_failure: LockRenewFailureCallback | None = None, executor: ThreadPoolExecutor | None = None, max_workers: int | None = None)[source]

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

Parameters:
  • max_lock_renewal_duration (float) – A time in seconds that locks registered to this renewer should be maintained for. Default value is 300 (5 minutes).

  • on_lock_renew_failure (Optional[LockRenewFailureCallback]) – A callback may be specified to be called when the lock is lost on the renewable that is being registered. Default value is None (no callback).

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

  • max_workers (Optional[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:

Automatically renew a message lock
from azure.servicebus import AutoLockRenewer
lock_renewal = AutoLockRenewer(max_workers=4)
with servicebus_receiver:
    for message in servicebus_receiver:
        # Auto renew message for 1 minute.
        lock_renewal.register(servicebus_receiver, message, max_lock_renewal_duration=60)
        process_message(message)
        servicebus_receiver.complete_message(message)
Automatically renew a session lock
    from azure.servicebus import AutoLockRenewer

    lock_renewal = AutoLockRenewer(max_workers=4)
    with servicebus_client.get_queue_receiver(queue_name=queue_name, session_id=session_id) as receiver:
        session = receiver.session
        # Auto renew session lock for 2 minutes
        lock_renewal.register(receiver, session, max_lock_renewal_duration=120)
        for message in receiver:
            process_message(message)
            receiver.complete_message(message)

Auto renew locks for messages and sessions using a background thread pool. It is recommended setting max_worker to a large number or passing ThreadPoolExecutor of large max_workers number when AutoLockRenewer is supposed to deal with multiple messages or sessions simultaneously.

Parameters:
  • max_lock_renewal_duration (float) – A time in seconds that locks registered to this renewer should be maintained for. Default value is 300 (5 minutes).

  • on_lock_renew_failure (Optional[LockRenewFailureCallback]) – A callback may be specified to be called when the lock is lost on the renewable that is being registered. Default value is None (no callback).

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

  • max_workers (Optional[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.

close(wait: bool = True) None[source]

Cease autorenewal by shutting down 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.

Return type:

None

register(receiver: ServiceBusReceiver, renewable: ServiceBusReceivedMessage | ServiceBusSession, max_lock_renewal_duration: float | None = None, on_lock_renew_failure: LockRenewFailureCallback | None = None) None[source]

Register a renewable entity for automatic lock renewal.

Parameters:
  • receiver (ServiceBusReceiver) – The ServiceBusReceiver instance that is associated with the message or the session to be auto-lock-renewed.

  • renewable (Union[ServiceBusReceivedMessage, ServiceBusSession]) – A locked entity that needs to be renewed.

  • max_lock_renewal_duration (Optional[float]) – A time in seconds that the lock should be maintained for. Default value is None. If specified, this value will override the default value specified at the constructor.

  • on_lock_renew_failure (Optional[LockRenewFailureCallback]) – A callback may be specified to be called when the lock is lost on the renewable that is being registered. Default value is None (no callback).

Return type:

None

class azure.servicebus.ServiceBusClient(fully_qualified_namespace: str, credential: TokenCredential | AzureSasCredential | AzureNamedKeyCredential, *, retry_total: int = 3, retry_backoff_factor: float = 0.8, retry_backoff_max: float = 120, retry_mode: str = 'exponential', **kwargs: Any)[source]

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 or AzureSasCredential or AzureNamedKeyCredential) – The credential object used for authentication which implements a particular interface for getting tokens. It accepts credential objects generated by the azure-identity library and objects that implement the get_token(self, *scopes) method, or alternatively, an AzureSasCredential can be provided too.

Keyword Arguments:
  • 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 in which case port 5671 is used. If the port 5671 is unavailable/blocked in the network environment, TransportType.AmqpOverWebsocket could be used instead which uses port 443 for communication.

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

  • user_agent (str) – If specified, this will be added in front of the built-in user agent string.

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

  • retry_backoff_factor (float) – Delta back-off internal in the unit of second between retries. Default value is 0.8.

  • retry_backoff_max (float) – Maximum back-off interval in the unit of second. Default value is 120.

  • retry_mode (str) – The delay behavior between retry attempts. Supported values are “fixed” or “exponential”, where default is “exponential”.

  • custom_endpoint_address (str) – The custom endpoint address to use for establishing a connection to the Service Bus service, allowing network requests to be routed through any application gateways or other paths needed for the host environment. Default is None. The format would be like “sb://<custom_endpoint_hostname>:<custom_endpoint_port>”. If port is not specified in the custom_endpoint_address, by default port 443 will be used.

  • connection_verify (str) – Path to the custom CA_BUNDLE file of the SSL certificate which is used to authenticate the identity of the connection endpoint. Default is None in which case certifi.where() will be used.

  • uamqp_transport (bool) – Whether to use the uamqp library as the underlying transport. The default value is False and the Pure Python AMQP library will be used as the underlying transport.

Example:

Create a new instance of the ServiceBusClient.
import os
from azure.identity import DefaultAzureCredential
from azure.servicebus import ServiceBusClient
fully_qualified_namespace = os.environ['SERVICEBUS_FULLY_QUALIFIED_NAMESPACE']
servicebus_client = ServiceBusClient(
    fully_qualified_namespace=fully_qualified_namespace,
    credential=DefaultAzureCredential()
)
close() None[source]

Close down the ServiceBus client. All spawned senders, receivers and underlying connection will be shutdown.

Returns:

None

classmethod from_connection_string(conn_str: str, *, retry_total: int = 3, retry_backoff_factor: float = 0.8, retry_backoff_max: float = 120, retry_mode: str = 'exponential', **kwargs: Any) ServiceBusClient[source]

Create a ServiceBusClient from a connection string.

Parameters:

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

Keyword Arguments:
  • 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 in which case port 5671 is used. If the port 5671 is unavailable/blocked in the network environment, TransportType.AmqpOverWebsocket could be used instead which uses port 443 for communication.

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

  • user_agent (str) – If specified, this will be added in front of the built-in user agent string.

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

  • retry_backoff_factor (float) – Delta back-off internal in the unit of second between retries. Default value is 0.8.

  • retry_backoff_max (float) – Maximum back-off interval in the unit of second. Default value is 120.

  • retry_mode (str) – The delay behavior between retry attempts. Supported values are ‘fixed’ or ‘exponential’, where default is ‘exponential’.

  • custom_endpoint_address (str) – The custom endpoint address to use for establishing a connection to the Service Bus service, allowing network requests to be routed through any application gateways or other paths needed for the host environment. Default is None. The format would be like “sb://<custom_endpoint_hostname>:<custom_endpoint_port>”. If port is not specified in the custom_endpoint_address, by default port 443 will be used.

  • connection_verify (str) – Path to the custom CA_BUNDLE file of the SSL certificate which is used to authenticate the identity of the connection endpoint. Default is None in which case certifi.where() will be used.

  • uamqp_transport (bool) – Whether to use the uamqp library as the underlying transport. The default value is False and the Pure Python AMQP library will be used as the underlying transport.

Return type:

ServiceBusClient

Example:

Create a new instance of the ServiceBusClient from connection string.
import os
from azure.servicebus import ServiceBusClient
servicebus_connection_str = os.environ['SERVICEBUS_CONNECTION_STR']
servicebus_client = ServiceBusClient.from_connection_string(conn_str=servicebus_connection_str)
get_queue_receiver(queue_name: str, *, session_id: str | ~typing.Literal[<ServiceBusSessionFilter.NEXT_AVAILABLE: 0>] | None = None, sub_queue: ~azure.servicebus._common.constants.ServiceBusSubQueue | str | None = None, receive_mode: ~azure.servicebus._common.constants.ServiceBusReceiveMode | str = ServiceBusReceiveMode.PEEK_LOCK, max_wait_time: float | None = None, auto_lock_renewer: ~azure.servicebus._common.auto_lock_renewer.AutoLockRenewer | None = None, prefetch_count: int = 0, **kwargs: ~typing.Any) ServiceBusReceiver[source]

Get ServiceBusReceiver for the specific queue.

Parameters:

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

Keyword Arguments:
  • session_id (str or NEXT_AVAILABLE_SESSION) – A specific session from which to receive. This must be specified for a sessionful queue, otherwise it must be None. In order to receive messages from the next available session, set this to ~azure.servicebus.NEXT_AVAILABLE_SESSION.

  • sub_queue (str or ServiceBusSubQueue or None) – If specified, the subqueue this receiver will connect to. This includes the DEAD_LETTER and TRANSFER_DEAD_LETTER queues, holds messages that can’t be delivered to any receiver or messages that can’t be processed. The default is None, meaning connect to the primary queue. Can be assigned values from ServiceBusSubQueue enum or equivalent string values “deadletter” and “transferdeadletter”.

  • receive_mode (Union[ServiceBusReceiveMode, str]) – The receive_mode with which messages will be retrieved from the entity. The two options are PEEK_LOCK and RECEIVE_AND_DELETE. Messages received with PEEK_LOCK must be settled within a given lock period before they will be removed from the queue. Messages received with RECEIVE_AND_DELETE 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 receive_mode is PEEK_LOCK.

  • max_wait_time (Optional[float]) – The timeout in seconds to wait for the first and subsequent messages to arrive. If no messages arrive, and no timeout is specified, this call will not return until the connection is closed. The default value is None, meaning no timeout. On a sessionful queue/topic when NEXT_AVAILABLE_SESSION is specified, this will act as the timeout for connecting. If connection errors are occurring due to write timing out,the connection timeout value may need to be adjusted. See the socket_timeout optional parameter for more details.

  • auto_lock_renewer (Optional[AutoLockRenewer]) – An ~azure.servicebus.AutoLockRenewer can be provided such that messages are automatically registered on receipt. If the receiver is a session receiver, it will apply to the session instead.

  • prefetch_count (int) – The maximum number of messages to cache with each request to the service. This setting is only for advanced performance tuning. Increasing this value will improve message throughput performance but increase the chance that messages will expire while they are cached if they’re not processed fast enough. The default value is 0, meaning messages will be received from the service and processed one at a time. In the case of prefetch_count being 0, ServiceBusReceiver.receive_messages would try to cache max_message_count (if provided) within its request to the service. **WARNING: If prefetch_count > 0 and RECEIVE_AND_DELETE mode is used, all prefetched messages will stay in the in-memory prefetch buffer until they’re received into the application. If the application ends before the messages are received into the application, those messages will be lost and unable to be recovered. Therefore, it’s recommended that PEEK_LOCK mode be used with prefetch.

  • client_identifier (str) – A string-based identifier to uniquely identify the receiver instance. Service Bus will associate it with some error messages for easier correlation of errors. If not specified, a unique id will be generated.

  • socket_timeout (float) – The time in seconds that the underlying socket on the connection should wait when sending and receiving data before timing out. The default value is 0.2 for TransportType.Amqp and 1 for TransportType.AmqpOverWebsocket. If connection errors are occurring due to write timing out, a larger than default value may need to be passed in.

Return type:

ServiceBusReceiver

Example:

Create a new instance of the ServiceBusReceiver from ServiceBusClient.
import os
from azure.servicebus import ServiceBusClient
servicebus_connection_str = os.environ['SERVICEBUS_CONNECTION_STR']
queue_name = os.environ['SERVICEBUS_QUEUE_NAME']
servicebus_client = ServiceBusClient.from_connection_string(conn_str=servicebus_connection_str)
with servicebus_client:
    queue_receiver = servicebus_client.get_queue_receiver(queue_name=queue_name)
get_queue_sender(queue_name: str, **kwargs: Any) 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:
  • client_identifier (str) – A string-based identifier to uniquely identify the sender instance. Service Bus will associate it with some error messages for easier correlation of errors. If not specified, a unique id will be generated.

  • socket_timeout (float) – The time in seconds that the underlying socket on the connection should wait when sending and receiving data before timing out. The default value is 0.2 for TransportType.Amqp and 1 for TransportType.AmqpOverWebsocket. If connection errors are occurring due to write timing out, a larger than default value may need to be passed in.

Returns:

A queue Sender.

Return type:

ServiceBusSender

Example:

Create a new instance of the ServiceBusSender from ServiceBusClient.
import os
from azure.servicebus import ServiceBusClient
servicebus_connection_str = os.environ['SERVICEBUS_CONNECTION_STR']
queue_name = os.environ['SERVICEBUS_QUEUE_NAME']
servicebus_client = ServiceBusClient.from_connection_string(conn_str=servicebus_connection_str)
with servicebus_client:
    queue_sender = servicebus_client.get_queue_sender(queue_name=queue_name)
get_subscription_receiver(topic_name: str, subscription_name: str, *, session_id: str | ~typing.Literal[<ServiceBusSessionFilter.NEXT_AVAILABLE: 0>] | None = None, sub_queue: ~azure.servicebus._common.constants.ServiceBusSubQueue | str | None = None, receive_mode: ~azure.servicebus._common.constants.ServiceBusReceiveMode | str = ServiceBusReceiveMode.PEEK_LOCK, max_wait_time: float | None = None, auto_lock_renewer: ~azure.servicebus._common.auto_lock_renewer.AutoLockRenewer | None = None, prefetch_count: int = 0, **kwargs: ~typing.Any) ServiceBusReceiver[source]

Get ServiceBusReceiver for the specific subscription under the topic.

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

  • subscription_name (str) – The name of specific Service Bus Subscription under the given Service Bus Topic.

Keyword Arguments:
  • session_id (str or NEXT_AVAILABLE_SESSION) – A specific session from which to receive. This must be specified for a sessionful subscription, otherwise it must be None. In order to receive messages from the next available session, set this to ~azure.servicebus.NEXT_AVAILABLE_SESSION.

  • sub_queue (str or ServiceBusSubQueue or None) – If specified, the subqueue this receiver will connect to. This includes the DEAD_LETTER and TRANSFER_DEAD_LETTER queues, holds messages that can’t be delivered to any receiver or messages that can’t be processed. The default is None, meaning connect to the primary queue. Can be assigned values from ServiceBusSubQueue enum or equivalent string values “deadletter” and “transferdeadletter”.

  • receive_mode (Union[ServiceBusReceiveMode, str]) – The receive_mode with which messages will be retrieved from the entity. The two options are PEEK_LOCK and RECEIVE_AND_DELETE. Messages received with PEEK_LOCK must be settled within a given lock period before they will be removed from the subscription. Messages received with RECEIVE_AND_DELETE will be immediately removed from the subscription, and cannot be subsequently rejected or re-received if the client fails to process the message. The default receive_mode is PEEK_LOCK.

  • max_wait_time (Optional[float]) – The timeout in seconds to wait for the first and subsequent messages to arrive. If no messages arrive, and no timeout is specified, this call will not return until the connection is closed. The default value is None, meaning no timeout. On a sessionful queue/topic when NEXT_AVAILABLE_SESSION is specified, this will act as the timeout for connecting. If connection errors are occurring due to write timing out,the connection timeout value may need to be adjusted. See the socket_timeout optional parameter for more details.

  • auto_lock_renewer (Optional[AutoLockRenewer]) – An ~azure.servicebus.AutoLockRenewer can be provided such that messages are automatically registered on receipt. If the receiver is a session receiver, it will apply to the session instead.

  • prefetch_count (int) – The maximum number of messages to cache with each request to the service. This setting is only for advanced performance tuning. Increasing this value will improve message throughput performance but increase the chance that messages will expire while they are cached if they’re not processed fast enough. The default value is 0, meaning messages will be received from the service and processed one at a time. In the case of prefetch_count being 0, ServiceBusReceiver.receive_messages would try to cache max_message_count (if provided) within its request to the service. **WARNING: If prefetch_count > 0 and RECEIVE_AND_DELETE mode is used, all prefetched messages will stay in the in-memory prefetch buffer until they’re received into the application. If the application ends before the messages are received into the application, those messages will be lost and unable to be recovered. Therefore, it’s recommended that PEEK_LOCK mode be used with prefetch.

  • client_identifier (str) – A string-based identifier to uniquely identify the receiver instance. Service Bus will associate it with some error messages for easier correlation of errors. If not specified, a unique id will be generated.

  • socket_timeout (float) – The time in seconds that the underlying socket on the connection should wait when sending and receiving data before timing out. The default value is 0.2 for TransportType.Amqp and 1 for TransportType.AmqpOverWebsocket. If connection errors are occurring due to write timing out, a larger than default value may need to be passed in.

Return type:

ServiceBusReceiver

Example:

Create a new instance of the ServiceBusReceiver from ServiceBusClient.
import os
from azure.servicebus import ServiceBusClient
servicebus_connection_str = os.environ['SERVICEBUS_CONNECTION_STR']
topic_name = os.environ["SERVICEBUS_TOPIC_NAME"]
subscription_name = os.environ["SERVICEBUS_SUBSCRIPTION_NAME"]
servicebus_client = ServiceBusClient.from_connection_string(conn_str=servicebus_connection_str)
with servicebus_client:
    subscription_receiver = servicebus_client.get_subscription_receiver(
        topic_name=topic_name,
        subscription_name=subscription_name,
    )
get_topic_sender(topic_name: str, *, client_identifier: str | None = None, socket_timeout: float | None = None, **kwargs: Any) ServiceBusSender[source]

Get ServiceBusSender for the specific topic.

Parameters:

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

Keyword Arguments:
  • client_identifier (str or None) – A string-based identifier to uniquely identify the sender instance. Service Bus will associate it with some error messages for easier correlation of errors. If not specified, a unique id will be generated.

  • socket_timeout (float or None) – The time in seconds that the underlying socket on the connection should wait when sending and receiving data before timing out. If None, a default value of 0.2 for TransportType.Amqp and 1 for TransportType.AmqpOverWebsocket is used. If connection errors are occurring due to write timing out, a larger than default value may need to be passed in.

Returns:

A topic sender.

Return type:

ServiceBusSender

Example:

Create a new instance of the ServiceBusSender from ServiceBusClient.
import os
from azure.servicebus import ServiceBusClient
servicebus_connection_str = os.environ['SERVICEBUS_CONNECTION_STR']
topic_name = os.environ['SERVICEBUS_TOPIC_NAME']
servicebus_client = ServiceBusClient.from_connection_string(conn_str=servicebus_connection_str)
with servicebus_client:
    topic_sender = servicebus_client.get_topic_sender(topic_name=topic_name)
class azure.servicebus.ServiceBusConnectionStringProperties(*, fully_qualified_namespace: str, endpoint: str, entity_path: str | None = None, shared_access_signature: str | None = None, shared_access_key_name: str | None = None, shared_access_key: str | None = None)[source]

Properties of a connection string.

get(key: str, default: Any | None = None) Any
has_key(k: str) bool
items() List[Tuple[str, Any]]
keys() List[str]
update(*args: Any, **kwargs: Any) None
values() List[Any]
property endpoint: str

//<FQDN>/ :rtype: str

Type:

The endpoint for the Service Bus resource. In the format sb

property entity_path: str | None

Optional. Represents the name of the queue/topic. :rtype: str or None

property fully_qualified_namespace: str

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

property shared_access_key: str | None

The shared_access_key can be used along with the shared_access_key_name as a credential. :rtype: str or None

property shared_access_key_name: str | None

The name of the shared_access_key. This must be used along with the shared_access_key. :rtype: str or None

property shared_access_signature: str | None

This can be provided instead of the shared_access_key_name and the shared_access_key. :rtype: str or None

class azure.servicebus.ServiceBusMessage(body: str | bytes | None, *, application_properties: Dict[str | bytes, int | float | bytes | bool | str | UUID] | None = None, session_id: str | None = None, message_id: str | None = None, scheduled_enqueue_time_utc: datetime | None = None, time_to_live: timedelta | None = None, content_type: str | None = None, correlation_id: str | None = None, subject: str | None = None, partition_key: str | None = None, to: str | None = None, reply_to: str | None = None, reply_to_session_id: str | None = None, **kwargs: Any)[source]

A Service Bus Message.

Parameters:

body (Optional[Union[str, bytes]]) – The data to send in a single message.

Keyword Arguments:
  • application_properties (Dict[str, Union[int or float or bool or bytes or str or uuid.UUID or datetime or None]]) – The user defined properties on the message.

  • session_id (Optional[str]) – The session identifier of the message for a sessionful entity.

  • message_id (Optional[str]) – The id to identify the message.

  • scheduled_enqueue_time_utc (Optional[datetime.datetime]) – The utc scheduled enqueue time to the message.

  • time_to_live (Optional[datetime.timedelta]) – The life duration of a message.

  • content_type (Optional[str]) – The content type descriptor.

  • correlation_id (Optional[str]) – The correlation identifier.

  • subject (Optional[str]) – The application specific subject, sometimes referred to as label.

  • partition_key (Optional[str]) – The partition key for sending a message to a partitioned entity.

  • to (Optional[str]) – The to address used for auto_forward chaining scenarios.

  • reply_to (Optional[str]) – The address of an entity to send replies to.

  • reply_to_session_id (Optional[str]) – The session identifier augmenting the reply_to address.

Example:

Sending a message with additional properties
message_send = ServiceBusMessage(
    "Hello World!!",
    session_id="MySessionID",
    application_properties={'data': 'custom_data'},
    time_to_live=datetime.timedelta(seconds=30),
    label='MyLabel'
)
property application_properties: Dict[str | bytes, int | float | bytes | bool | str | UUID] | None

The user defined properties on the message.

Return type:

dict[str or bytes, PrimitiveTypes] or None

property body: Any

The body of the Message. The format may vary depending on the body type: For azure.servicebus.amqp.AmqpMessageBodyType.DATA, the body could be bytes or Iterable[bytes]. For azure.servicebus.amqp.AmqpMessageBodyType.SEQUENCE, the body could be List or Iterable[List]. For azure.servicebus.amqp.AmqpMessageBodyType.VALUE, the body could be any type.

Return type:

Any

property body_type: AmqpMessageBodyType

The body type of the underlying AMQP message.

Return type:

AmqpMessageBodyType

property content_type: str | None

The content type descriptor.

Optionally describes the payload of the message, with a descriptor following the format of RFC2045, Section 5, for example “application/json”.

Return type:

str or None

property correlation_id: str | None

The correlation identifier.

Allows an application to specify a context for the message for the purposes of correlation, for example reflecting the MessageId of a message that is being replied to.

See Message Routing and Correlation in https://docs.microsoft.com/azure/service-bus-messaging/service-bus-messages-payloads?#message-routing-and-correlation.

Return type:

str or None

property message: 'Message' | LegacyMessage
Get the underlying uamqp.Message or LegacyMessage.

This is deprecated and will be removed in a later release.

Return type:

uamqp.Message or LegacyMessage

Type:

DEPRECATED

property message_id: str | None

The id to identify the message.

The message identifier is an application-defined value that uniquely identifies the message and its payload. The identifier is a free-form string and can reflect a GUID or an identifier derived from the application context. If enabled, the duplicate detection (see https://docs.microsoft.com/azure/service-bus-messaging/duplicate-detection) feature identifies and removes second and further submissions of messages with the same message id.

Return type:

str or None

property partition_key: str | None

The partition key for sending a message to a partitioned entity.

Setting this value enables assigning related messages to the same internal partition, so that submission sequence order is correctly recorded. The partition is chosen by a hash function over this value and cannot be chosen directly.

See Partitioned queues and topics in https://docs.microsoft.com/azure/service-bus-messaging/service-bus-partitioning.

Return type:

str or None

property raw_amqp_message: AmqpAnnotatedMessage

Advanced usage only. The internal AMQP message payload that is sent or received. :rtype: ~azure.servicebus.amqp.AmqpAnnotatedMessage

property reply_to: str | None

The address of an entity to send replies to.

This optional and application-defined value is a standard way to express a reply path to the receiver of the message. When a sender expects a reply, it sets the value to the absolute or relative path of the queue or topic it expects the reply to be sent to.

See Message Routing and Correlation in https://docs.microsoft.com/azure/service-bus-messaging/service-bus-messages-payloads?#message-routing-and-correlation.

Return type:

str or None

property reply_to_session_id: str | None

The session identifier augmenting the reply_to address.

This value augments the reply_to information and specifies which session id should be set for the reply when sent to the reply entity.

See Message Routing and Correlation in https://docs.microsoft.com/azure/service-bus-messaging/service-bus-messages-payloads?#message-routing-and-correlation.

Return type:

str or None

property scheduled_enqueue_time_utc: datetime | None

The utc scheduled enqueue time to the message.

This property can be used for scheduling when sending a message through ServiceBusSender.send method. If cancelling scheduled messages is required, you should use the ServiceBusSender.schedule method, which returns sequence numbers that can be used for future cancellation. scheduled_enqueue_time_utc is None if not set.

Return type:

datetime

property session_id: str | None

The session identifier of the message for a sessionful entity.

For sessionful entities, this application-defined value specifies the session affiliation of the message. Messages with the same session identifier are subject to summary locking and enable exact in-order processing and demultiplexing. For non-sessionful entities, this value is ignored.

See Message Sessions in https://docs.microsoft.com/azure/service-bus-messaging/message-sessions.

Return type:

str or None

property subject: str | None

The application specific subject, sometimes referred to as a label.

This property enables the application to indicate the purpose of the message to the receiver in a standardized fashion, similar to an email subject line.

Return type:

str

property time_to_live: timedelta | None

The life duration of a message.

This value is the relative duration after which the message expires, starting from the instant the message has been accepted and stored by the broker, as captured in enqueued_time_utc. When not set explicitly, the assumed value is the DefaultTimeToLive for the respective queue or topic. A message-level time-to-live value cannot be longer than the entity’s time-to-live setting and it is silently adjusted if it does.

See Expiration in https://docs.microsoft.com/azure/service-bus-messaging/message-expiration

Return type:

timedelta

property to: str | None

The to address.

This property is reserved for future use in routing scenarios and presently ignored by the broker itself. Applications can use this value in rule-driven auto-forward chaining scenarios to indicate the intended logical destination of the message.

See https://docs.microsoft.com/azure/service-bus-messaging/service-bus-auto-forwarding for more details.

Return type:

str or None

class azure.servicebus.ServiceBusMessageBatch(max_size_in_bytes: int | None = None, **kwargs: Any)[source]

A batch of messages.

Sending messages in a batch is more performant than sending individual message. ServiceBusMessageBatch 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 MessageSizeExceededError will be raised.

Please use the create_message_batch method of ServiceBusSender to create a ServiceBusMessageBatch object instead of instantiating a ServiceBusMessageBatch object directly.

Parameters:

max_size_in_bytes (Optional[int]) – The maximum size of bytes data that a ServiceBusMessageBatch object can hold.

add_message(message: ServiceBusMessage | AmqpAnnotatedMessage | Mapping[str, Any]) 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 MessageSizeExceededError will be raised.

Parameters:

message (Union[ServiceBusMessage, AmqpAnnotatedMessage]) – The Message to be added to the batch.

Raises:
class:

~azure.servicebus.exceptions.MessageSizeExceededError, when exceeding the size limit.

property max_size_in_bytes: int

The maximum size of bytes data that a ServiceBusMessageBatch object can hold.

Return type:

int

property message: 'BatchMessage' | LegacyBatchMessage
Get the underlying uamqp.BatchMessage or LegacyBatchMessage.

This is deprecated and will be removed in a later release.

Return type:

BatchMessage or LegacyBatchMessage

Type:

DEPRECATED

property size_in_bytes: int

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

Return type:

int

class azure.servicebus.ServiceBusMessageState(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]
as_integer_ratio()

Return integer ratio.

Return a pair of integers, whose ratio is exactly equal to the original int and with a positive denominator.

>>> (10).as_integer_ratio()
(10, 1)
>>> (-10).as_integer_ratio()
(-10, 1)
>>> (0).as_integer_ratio()
(0, 1)
bit_count()

Number of ones in the binary representation of the absolute value of self.

Also known as the population count.

>>> bin(13)
'0b1101'
>>> (13).bit_count()
3
bit_length()

Number of bits necessary to represent self in binary.

>>> bin(37)
'0b100101'
>>> (37).bit_length()
6
conjugate()

Returns self, the complex conjugate of any int.

from_bytes(byteorder='big', *, signed=False)

Return the integer represented by the given array of bytes.

bytes

Holds the array of bytes to convert. The argument must either support the buffer protocol or be an iterable object producing bytes. Bytes and bytearray are examples of built-in objects that support the buffer protocol.

byteorder

The byte order used to represent the integer. If byteorder is ‘big’, the most significant byte is at the beginning of the byte array. If byteorder is ‘little’, the most significant byte is at the end of the byte array. To request the native byte order of the host system, use `sys.byteorder’ as the byte order value. Default is to use ‘big’.

signed

Indicates whether two’s complement is used to represent the integer.

to_bytes(length=1, byteorder='big', *, signed=False)

Return an array of bytes representing an integer.

length

Length of bytes object to use. An OverflowError is raised if the integer is not representable with the given number of bytes. Default is length 1.

byteorder

The byte order used to represent the integer. If byteorder is ‘big’, the most significant byte is at the beginning of the byte array. If byteorder is ‘little’, the most significant byte is at the end of the byte array. To request the native byte order of the host system, use `sys.byteorder’ as the byte order value. Default is to use ‘big’.

signed

Determines whether two’s complement is used to represent the integer. If signed is False and a negative integer is given, an OverflowError is raised.

ACTIVE = 0
DEFERRED = 1
SCHEDULED = 2
denominator

the denominator of a rational number in lowest terms

imag

the imaginary part of a complex number

numerator

the numerator of a rational number in lowest terms

real

the real part of a complex number

class azure.servicebus.ServiceBusReceiveMode(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]
capitalize()

Return a capitalized version of the string.

More specifically, make the first character have upper case and the rest lower case.

casefold()

Return a version of the string suitable for caseless comparisons.

center(width, fillchar=' ', /)

Return a centered string of length width.

Padding is done using the specified fill character (default is a space).

count(sub[, start[, end]]) int

Return the number of non-overlapping occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation.

encode(encoding='utf-8', errors='strict')

Encode the string using the codec registered for encoding.

encoding

The encoding in which to encode the string.

errors

The error handling scheme to use for encoding errors. The default is ‘strict’ meaning that encoding errors raise a UnicodeEncodeError. Other possible values are ‘ignore’, ‘replace’ and ‘xmlcharrefreplace’ as well as any other name registered with codecs.register_error that can handle UnicodeEncodeErrors.

endswith(suffix[, start[, end]]) bool

Return True if S ends with the specified suffix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. suffix can also be a tuple of strings to try.

expandtabs(tabsize=8)

Return a copy where all tab characters are expanded using spaces.

If tabsize is not given, a tab size of 8 characters is assumed.

find(sub[, start[, end]]) int

Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Return -1 on failure.

format(*args, **kwargs) str

Return a formatted version of S, using substitutions from args and kwargs. The substitutions are identified by braces (‘{’ and ‘}’).

format_map(mapping) str

Return a formatted version of S, using substitutions from mapping. The substitutions are identified by braces (‘{’ and ‘}’).

index(sub[, start[, end]]) int

Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Raises ValueError when the substring is not found.

isalnum()

Return True if the string is an alpha-numeric string, False otherwise.

A string is alpha-numeric if all characters in the string are alpha-numeric and there is at least one character in the string.

isalpha()

Return True if the string is an alphabetic string, False otherwise.

A string is alphabetic if all characters in the string are alphabetic and there is at least one character in the string.

isascii()

Return True if all characters in the string are ASCII, False otherwise.

ASCII characters have code points in the range U+0000-U+007F. Empty string is ASCII too.

isdecimal()

Return True if the string is a decimal string, False otherwise.

A string is a decimal string if all characters in the string are decimal and there is at least one character in the string.

isdigit()

Return True if the string is a digit string, False otherwise.

A string is a digit string if all characters in the string are digits and there is at least one character in the string.

isidentifier()

Return True if the string is a valid Python identifier, False otherwise.

Call keyword.iskeyword(s) to test whether string s is a reserved identifier, such as “def” or “class”.

islower()

Return True if the string is a lowercase string, False otherwise.

A string is lowercase if all cased characters in the string are lowercase and there is at least one cased character in the string.

isnumeric()

Return True if the string is a numeric string, False otherwise.

A string is numeric if all characters in the string are numeric and there is at least one character in the string.

isprintable()

Return True if the string is printable, False otherwise.

A string is printable if all of its characters are considered printable in repr() or if it is empty.

isspace()

Return True if the string is a whitespace string, False otherwise.

A string is whitespace if all characters in the string are whitespace and there is at least one character in the string.

istitle()

Return True if the string is a title-cased string, False otherwise.

In a title-cased string, upper- and title-case characters may only follow uncased characters and lowercase characters only cased ones.

isupper()

Return True if the string is an uppercase string, False otherwise.

A string is uppercase if all cased characters in the string are uppercase and there is at least one cased character in the string.

join(iterable, /)

Concatenate any number of strings.

The string whose method is called is inserted in between each given string. The result is returned as a new string.

Example: ‘.’.join([‘ab’, ‘pq’, ‘rs’]) -> ‘ab.pq.rs’

ljust(width, fillchar=' ', /)

Return a left-justified string of length width.

Padding is done using the specified fill character (default is a space).

lower()

Return a copy of the string converted to lowercase.

lstrip(chars=None, /)

Return a copy of the string with leading whitespace removed.

If chars is given and not None, remove characters in chars instead.

static maketrans()

Return a translation table usable for str.translate().

If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters to Unicode ordinals, strings or None. Character keys will be then converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result.

partition(sep, /)

Partition the string into three parts using the given separator.

This will search for the separator in the string. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.

If the separator is not found, returns a 3-tuple containing the original string and two empty strings.

removeprefix(prefix, /)

Return a str with the given prefix string removed if present.

If the string starts with the prefix string, return string[len(prefix):]. Otherwise, return a copy of the original string.

removesuffix(suffix, /)

Return a str with the given suffix string removed if present.

If the string ends with the suffix string and that suffix is not empty, return string[:-len(suffix)]. Otherwise, return a copy of the original string.

replace(old, new, count=-1, /)

Return a copy with all occurrences of substring old replaced by new.

count

Maximum number of occurrences to replace. -1 (the default value) means replace all occurrences.

If the optional argument count is given, only the first count occurrences are replaced.

rfind(sub[, start[, end]]) int

Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Return -1 on failure.

rindex(sub[, start[, end]]) int

Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Raises ValueError when the substring is not found.

rjust(width, fillchar=' ', /)

Return a right-justified string of length width.

Padding is done using the specified fill character (default is a space).

rpartition(sep, /)

Partition the string into three parts using the given separator.

This will search for the separator in the string, starting at the end. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.

If the separator is not found, returns a 3-tuple containing two empty strings and the original string.

rsplit(sep=None, maxsplit=-1)

Return a list of the substrings in the string, using sep as the separator string.

sep

The separator used to split the string.

When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.

maxsplit

Maximum number of splits. -1 (the default value) means no limit.

Splitting starts at the end of the string and works to the front.

rstrip(chars=None, /)

Return a copy of the string with trailing whitespace removed.

If chars is given and not None, remove characters in chars instead.

split(sep=None, maxsplit=-1)

Return a list of the substrings in the string, using sep as the separator string.

sep

The separator used to split the string.

When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.

maxsplit

Maximum number of splits. -1 (the default value) means no limit.

Splitting starts at the front of the string and works to the end.

Note, str.split() is mainly useful for data that has been intentionally delimited. With natural text that includes punctuation, consider using the regular expression module.

splitlines(keepends=False)

Return a list of the lines in the string, breaking at line boundaries.

Line breaks are not included in the resulting list unless keepends is given and true.

startswith(prefix[, start[, end]]) bool

Return True if S starts with the specified prefix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. prefix can also be a tuple of strings to try.

strip(chars=None, /)

Return a copy of the string with leading and trailing whitespace removed.

If chars is given and not None, remove characters in chars instead.

swapcase()

Convert uppercase characters to lowercase and lowercase characters to uppercase.

title()

Return a version of the string where each word is titlecased.

More specifically, words start with uppercased characters and all remaining cased characters have lower case.

translate(table, /)

Replace each character in the string using the given translation table.

table

Translation table, which must be a mapping of Unicode ordinals to Unicode ordinals, strings, or None.

The table must implement lookup/indexing via __getitem__, for instance a dictionary or list. If this operation raises LookupError, the character is left untouched. Characters mapped to None are deleted.

upper()

Return a copy of the string converted to uppercase.

zfill(width, /)

Pad a numeric string with zeros on the left, to fill a field of the given width.

The string is never truncated.

PEEK_LOCK = 'peeklock'
RECEIVE_AND_DELETE = 'receiveanddelete'
class azure.servicebus.ServiceBusReceivedMessage(message: 'Message' | 'pyamqp_Message', receive_mode: ServiceBusReceiveMode | str = ServiceBusReceiveMode.PEEK_LOCK, frame: 'TransferFrame' | None = None, **kwargs: Any)[source]

A Service Bus Message received from service side.

Variables:

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

Example:

Checking the properties on a received message.
    from typing import List
    from azure.servicebus import ServiceBusReceivedMessage
    messages_complex: List[ServiceBusReceivedMessage] = servicebus_receiver.receive_messages(max_wait_time=5)
    for message in messages_complex:
        print("Receiving: {}".format(message))
        print("Time to live: {}".format(message.time_to_live))
        print("Sequence number: {}".format(message.sequence_number))
        print("Enqueued Sequence number: {}".format(message.enqueued_sequence_number))
        print("Partition Key: {}".format(message.partition_key))
        print("Application Properties: {}".format(message.application_properties))
        print("Delivery count: {}".format(message.delivery_count))
        print("Message ID: {}".format(message.message_id))
        print("Locked until: {}".format(message.locked_until_utc))
        print("Lock Token: {}".format(message.lock_token))
        print("Enqueued time: {}".format(message.enqueued_time_utc))
property application_properties: Dict[str | bytes, int | float | bytes | bool | str | UUID] | None

The user defined properties on the message.

Return type:

dict[str or bytes, PrimitiveTypes] or None

property body: Any

The body of the Message. The format may vary depending on the body type: For azure.servicebus.amqp.AmqpMessageBodyType.DATA, the body could be bytes or Iterable[bytes]. For azure.servicebus.amqp.AmqpMessageBodyType.SEQUENCE, the body could be List or Iterable[List]. For azure.servicebus.amqp.AmqpMessageBodyType.VALUE, the body could be any type.

Return type:

Any

property body_type: AmqpMessageBodyType

The body type of the underlying AMQP message.

Return type:

AmqpMessageBodyType

property content_type: str | None

The content type descriptor.

Optionally describes the payload of the message, with a descriptor following the format of RFC2045, Section 5, for example “application/json”.

Return type:

str or None

property correlation_id: str | None

The correlation identifier.

Allows an application to specify a context for the message for the purposes of correlation, for example reflecting the MessageId of a message that is being replied to.

See Message Routing and Correlation in https://docs.microsoft.com/azure/service-bus-messaging/service-bus-messages-payloads?#message-routing-and-correlation.

Return type:

str or None

property dead_letter_error_description: str | None

Dead letter error description, when the message is received from a deadletter subqueue of an entity.

Return type:

str

property dead_letter_reason: str | None

Dead letter reason, when the message is received from a deadletter subqueue of an entity.

Return type:

str

property dead_letter_source: str | None

The name of the queue or subscription that this message was enqueued on, before it was deadlettered. This property is only set in messages that have been dead-lettered and subsequently auto-forwarded from the dead-letter queue to another entity. Indicates the entity in which the message was dead-lettered.

Return type:

str

property delivery_count: int | None

Number of deliveries that have been attempted for this message. The count is incremented when a message lock expires or the message is explicitly abandoned by the receiver.

Return type:

int

property enqueued_sequence_number: int | None

For messages that have been auto-forwarded, this property reflects the sequence number that had first been assigned to the message at its original point of submission.

Return type:

int

property enqueued_time_utc: datetime | None

The UTC datetime at which the message has been accepted and stored in the entity.

Return type:

datetime

property expires_at_utc: datetime | None

The UTC datetime at which the message is marked for removal and no longer available for retrieval from the entity due to expiration. Expiry is controlled by the Message.time_to_live property. This property is computed from Message.enqueued_time_utc + Message.time_to_live.

Return type:

datetime

property lock_token: UUID | str | None

The lock token for the current message serving as a reference to the lock that is being held by the broker in PEEK_LOCK mode.

Return type:

UUID or str

property locked_until_utc: datetime | None

The UTC datetime until which the message will be locked in the queue/subscription. When the lock expires, delivery count of the message is incremented and the message is again available for retrieval.

Return type:

datetime.datetime

property message: 'Message' | LegacyMessage
Get the underlying LegacyMessage.

This is deprecated and will be removed in a later release.

Return type:

LegacyMessage

Type:

DEPRECATED

property message_id: str | None

The id to identify the message.

The message identifier is an application-defined value that uniquely identifies the message and its payload. The identifier is a free-form string and can reflect a GUID or an identifier derived from the application context. If enabled, the duplicate detection (see https://docs.microsoft.com/azure/service-bus-messaging/duplicate-detection) feature identifies and removes second and further submissions of messages with the same message id.

Return type:

str or None

property partition_key: str | None

The partition key for sending a message to a partitioned entity.

Setting this value enables assigning related messages to the same internal partition, so that submission sequence order is correctly recorded. The partition is chosen by a hash function over this value and cannot be chosen directly.

See Partitioned queues and topics in https://docs.microsoft.com/azure/service-bus-messaging/service-bus-partitioning.

Return type:

str or None

property raw_amqp_message: AmqpAnnotatedMessage

Advanced usage only. The internal AMQP message payload that is sent or received. :rtype: ~azure.servicebus.amqp.AmqpAnnotatedMessage

property reply_to: str | None

The address of an entity to send replies to.

This optional and application-defined value is a standard way to express a reply path to the receiver of the message. When a sender expects a reply, it sets the value to the absolute or relative path of the queue or topic it expects the reply to be sent to.

See Message Routing and Correlation in https://docs.microsoft.com/azure/service-bus-messaging/service-bus-messages-payloads?#message-routing-and-correlation.

Return type:

str or None

property reply_to_session_id: str | None

The session identifier augmenting the reply_to address.

This value augments the reply_to information and specifies which session id should be set for the reply when sent to the reply entity.

See Message Routing and Correlation in https://docs.microsoft.com/azure/service-bus-messaging/service-bus-messages-payloads?#message-routing-and-correlation.

Return type:

str or None

property scheduled_enqueue_time_utc: datetime | None

The utc scheduled enqueue time to the message.

This property can be used for scheduling when sending a message through ServiceBusSender.send method. If cancelling scheduled messages is required, you should use the ServiceBusSender.schedule method, which returns sequence numbers that can be used for future cancellation. scheduled_enqueue_time_utc is None if not set.

Return type:

datetime

property sequence_number: int | None

The unique number assigned to a message by Service Bus. The sequence number is a unique 64-bit integer assigned to a message as it is accepted and stored by the broker and functions as its true identifier. For partitioned entities, the topmost 16 bits reflect the partition identifier. Sequence numbers monotonically increase. They roll over to 0 when the 48-64 bit range is exhausted.

Return type:

int

property session_id: str | None

The session identifier of the message for a sessionful entity.

For sessionful entities, this application-defined value specifies the session affiliation of the message. Messages with the same session identifier are subject to summary locking and enable exact in-order processing and demultiplexing. For non-sessionful entities, this value is ignored.

See Message Sessions in https://docs.microsoft.com/azure/service-bus-messaging/message-sessions.

Return type:

str or None

property state: ServiceBusMessageState

Defaults to Active. Represents the message state of the message. Can be Active, Deferred. or Scheduled.

Return type:

ServiceBusMessageState

property subject: str | None

The application specific subject, sometimes referred to as a label.

This property enables the application to indicate the purpose of the message to the receiver in a standardized fashion, similar to an email subject line.

Return type:

str

property time_to_live: timedelta | None

The life duration of a message.

This value is the relative duration after which the message expires, starting from the instant the message has been accepted and stored by the broker, as captured in enqueued_time_utc. When not set explicitly, the assumed value is the DefaultTimeToLive for the respective queue or topic. A message-level time-to-live value cannot be longer than the entity’s time-to-live setting and it is silently adjusted if it does.

See Expiration in https://docs.microsoft.com/azure/service-bus-messaging/message-expiration

Return type:

timedelta

property to: str | None

The to address.

This property is reserved for future use in routing scenarios and presently ignored by the broker itself. Applications can use this value in rule-driven auto-forward chaining scenarios to indicate the intended logical destination of the message.

See https://docs.microsoft.com/azure/service-bus-messaging/service-bus-auto-forwarding for more details.

Return type:

str or None

class azure.servicebus.ServiceBusReceiver(fully_qualified_namespace: str, credential: TokenCredential | AzureSasCredential | AzureNamedKeyCredential, *, queue_name: str | None = None, topic_name: str | None = None, subscription_name: str | None = None, receive_mode: ServiceBusReceiveMode | str = ServiceBusReceiveMode.PEEK_LOCK, max_wait_time: float | None = None, auto_lock_renewer: AutoLockRenewer | None = None, prefetch_count: int = 0, **kwargs: Any)[source]

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

The two primary channels for message receipt are receive() to make a single request for messages, and for message in receiver: to continuously receive incoming messages in an ongoing fashion.

Please use the `get_<queue/subscription>_receiver` method of ~azure.servicebus.ServiceBusClient to create a ServiceBusReceiver instance.

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 or AzureSasCredential or AzureNamedKeyCredential) – The credential object used for authentication which implements a particular interface for getting tokens. It accepts credential objects generated by the azure-identity library and objects that implement the get_token(self, *scopes) method, or alternatively, an AzureSasCredential can be provided too.

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.

  • max_wait_time (Optional[float]) – The timeout in seconds to wait for the first and subsequent messages to arrive. If no messages arrive, and no timeout is specified, this call will not return until the connection is closed. The default value is None, meaning no timeout. On a sessionful queue/topic when NEXT_AVAILABLE_SESSION is specified, this will act as the timeout for connecting to a session. If connection errors are occurring due to write timing out,the connection timeout value may need to be adjusted. See the socket_timeout optional parameter for more details.

  • receive_mode (Union[ServiceBusReceiveMode, str]) – The mode with which messages will be retrieved from the entity. The two options are PEEK_LOCK and RECEIVE_AND_DELETE. Messages received with PEEK_LOCK must be settled within a given lock period before they will be removed from the queue. Messages received with RECEIVE_AND_DELETE will be immediately removed from the queue, and cannot be subsequently abandoned or re-received if the client fails to process the message. The default mode is PEEK_LOCK.

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

  • user_agent (str) – If specified, this will be added in front of the built-in user agent string.

  • auto_lock_renewer (Optional[AutoLockRenewer]) – An ~azure.servicebus.AutoLockRenewer can be provided such that messages are automatically registered on receipt. If the receiver is a session receiver, it will apply to the session instead.

  • prefetch_count (int) – The maximum number of messages to cache with each request to the service. This setting is only for advanced performance tuning. Increasing this value will improve message throughput performance but increase the chance that messages will expire while they are cached if they’re not processed fast enough. The default value is 0, meaning messages will be received from the service and processed one at a time. In the case of prefetch_count being 0, ServiceBusReceiver.receive_messages would try to cache max_message_count (if provided) within its request to the service. **WARNING: If prefetch_count > 0 and RECEIVE_AND_DELETE mode is used, all prefetched messages will stay in the in-memory prefetch buffer until they’re received into the application. If the application ends before the messages are received into the application, those messages will be lost and unable to be recovered. Therefore, it’s recommended that PEEK_LOCK mode be used with prefetch.

  • client_identifier (str) – A string-based identifier to uniquely identify the client instance. Service Bus will associate it with some error messages for easier correlation of errors. If not specified, a unique id will be generated.

  • socket_timeout (float) – The time in seconds that the underlying socket on the connection should wait when sending and receiving data before timing out. The default value is 0.2 for TransportType.Amqp and 1 for TransportType.AmqpOverWebsocket. If connection errors are occurring due to write timing out, a larger than default value may need to be passed in.

abandon_message(message: ServiceBusReceivedMessage) None[source]

Abandon the message.

This message will be returned to the queue and made available to be received again.

Parameters:

message (ServiceBusReceivedMessage) – The received message to be abandoned.

Return type:

None

Raises:

~azure.servicebus.exceptions.MessageAlreadySettled if the message has been settled.

Raises:

~azure.servicebus.exceptions.SessionLockLostError if session lock has already expired.

Raises:

~azure.servicebus.exceptions.ServiceBusError when errors happen.

Example:

Abandon a received message.
    messages_abandon = servicebus_receiver.receive_messages(max_wait_time=5)
    for message in messages_abandon:
        servicebus_receiver.abandon_message(message)
close() None[source]

Close down the handler links (and connection if the handler uses a separate connection).

If the handler has already closed, this operation will do nothing.

Return type:

None

complete_message(message: ServiceBusReceivedMessage) None[source]

Complete the message.

This removes the message from the queue.

Parameters:

message (ServiceBusReceivedMessage) – The received message to be completed.

Return type:

None

Raises:

~azure.servicebus.exceptions.MessageAlreadySettled if the message has been settled.

Raises:

~azure.servicebus.exceptions.SessionLockLostError if session lock has already expired.

Raises:

~azure.servicebus.exceptions.ServiceBusError when errors happen.

Example:

Complete a received message.
    messages_complete = servicebus_receiver.receive_messages(max_wait_time=5)
    for message in messages_complete:
        servicebus_receiver.complete_message(message)
dead_letter_message(message: ServiceBusReceivedMessage, reason: str | None = None, error_description: str | None = 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:
  • message (ServiceBusReceivedMessage) – The received message to be dead-lettered.

  • reason (Optional[str]) – The reason for dead-lettering the message.

  • error_description (Optional[str]) – The detailed error description for dead-lettering the message.

Return type:

None

Raises:

~azure.servicebus.exceptions.MessageAlreadySettled if the message has been settled.

Raises:

~azure.servicebus.exceptions.SessionLockLostError if session lock has already expired.

Raises:

~azure.servicebus.exceptions.ServiceBusError when errors happen.

Example:

Dead letter a received message.
    messages_dead_letter = servicebus_receiver.receive_messages(max_wait_time=5)
    for message in messages_dead_letter:
        servicebus_receiver.dead_letter_message(message)
defer_message(message: ServiceBusReceivedMessage) None[source]

Defers the message.

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

Parameters:

message (ServiceBusReceivedMessage) – The received message to be deferred.

Return type:

None

Raises:

~azure.servicebus.exceptions.MessageAlreadySettled if the message has been settled.

Raises:

~azure.servicebus.exceptions.SessionLockLostError if session lock has already expired.

Raises:

~azure.servicebus.exceptions.ServiceBusError when errors happen.

Example:

Defer a received message.
    messages_defer = servicebus_receiver.receive_messages(max_wait_time=5)
    for message in messages_defer:
        servicebus_receiver.defer_message(message)
next() ServiceBusReceivedMessage
peek_messages(max_message_count: int = 1, *, sequence_number: int = 0, timeout: float | None = None, **kwargs: Any) List[ServiceBusReceivedMessage][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:

max_message_count (int) – The maximum number of messages to try and peek. The default value is 1.

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

  • timeout (Optional[float]) – The total operation timeout in seconds including all the retries. The value must be greater than 0 if specified. The default value is None, meaning no timeout.

Returns:

A list of ~azure.servicebus.ServiceBusReceivedMessage.

Return type:

list[ServiceBusReceivedMessage]

Example:

Look at pending messages in the queue.
with servicebus_receiver:
    messages_peek = servicebus_receiver.peek_messages()
    for message in messages_peek:
        print(str(message))
receive_deferred_messages(sequence_numbers: int | List[int], *, timeout: float | None = None, **kwargs: Any) List[ServiceBusReceivedMessage][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 (Union[int,List[int]]) – A list of the sequence numbers of messages that have been deferred.

Keyword Arguments:

timeout (Optional[float]) – The total operation timeout in seconds including all the retries. The value must be greater than 0 if specified. The default value is None, meaning no timeout.

Returns:

A list of the requested ~azure.servicebus.ServiceBusReceivedMessage instances.

Return type:

list[ServiceBusReceivedMessage]

Example:

Receive deferred messages from ServiceBus.
with servicebus_receiver:
    deferred_sequenced_numbers = []
    messages_defer = servicebus_receiver.receive_messages(max_wait_time=5)
    for message in messages_defer:
        deferred_sequenced_numbers.append(message.sequence_number)
        print(str(message))
        servicebus_receiver.defer_message(message)

    received_deferred_msg = servicebus_receiver.receive_deferred_messages(
        sequence_numbers=deferred_sequenced_numbers
    )

    for msg in received_deferred_msg:
        servicebus_receiver.complete_message(msg)
receive_messages(max_message_count: int | None = 1, max_wait_time: float | None = None) List[ServiceBusReceivedMessage][source]

Receive a batch of messages at once.

This approach is optimal if you wish to process multiple messages simultaneously, or perform an ad-hoc receive as a single call.

Note that the number of messages retrieved in a single batch will be dependent on whether prefetch_count was set for the receiver. If prefetch_count is not set for the receiver, the receiver would try to cache max_message_count (if provided) messages within the request to the service.

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_message_count (Optional[int]) – Maximum number of messages in the batch. Actual number returned will depend on prefetch_count and incoming stream rate. Setting to None will fully depend on the prefetch config. The default value is 1.

  • max_wait_time (Optional[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, and no messages arrive within the timeout period, an empty list will be returned. NOTE: Setting max_wait_time on receive_messages when NEXT_AVAILABLE_SESSION is specified will not impact the timeout for connecting to a session. Please use max_wait_time on the constructor to set the timeout for connecting to a session.

Returns:

A list of messages received. If no messages are available, this will be an empty list.

Return type:

List[ServiceBusReceivedMessage]

Example:

Receive messages from ServiceBus.
with servicebus_receiver:
    messages_sync = servicebus_receiver.receive_messages(max_wait_time=5)
    for message in messages_sync:
        print(str(message))
        servicebus_receiver.complete_message(message)
renew_message_lock(message: ServiceBusReceivedMessage, *, timeout: float | None = None, **kwargs: Any) datetime[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, and cannot already have expired; an expired lock cannot be renewed.

Messages received via RECEIVE_AND_DELETE mode are not locked, and therefore cannot be renewed. This operation is only available for non-sessionful messages as well.

Parameters:

message (ServiceBusReceivedMessage) – The message to renew the lock for.

Keyword Arguments:

timeout (Optional[float]) – The total operation timeout in seconds including all the retries. The value must be greater than 0 if specified. The default value is None, meaning no timeout.

Returns:

The utc datetime the lock is set to expire at.

Return type:

datetime.datetime

Raises:

TypeError if the message is sessionful.

Raises:

~azure.servicebus.exceptions.MessageAlreadySettled if the message has been settled.

Raises:

~azure.servicebus.exceptions.MessageLockLostError if message lock has already expired.

Example:

Renew the lock on a received message.
    messages_lock = servicebus_receiver.receive_messages(max_wait_time=5)
    for message in messages_lock:
        servicebus_receiver.renew_message_lock(message)
property client_identifier: str

Get the ServiceBusReceiver client_identifier associated with the receiver instance.

Return type:

str

property session: ServiceBusSession

Get the ServiceBusSession object linked with the receiver. Session is only available to session-enabled entities, it would return None if called on a non-sessionful receiver.

Return type:

ServiceBusSession

Example:

Get session from a receiver
    with servicebus_client.get_queue_receiver(queue_name=queue_name, session_id=session_id) as receiver:
        session = receiver.session
class azure.servicebus.ServiceBusSender(fully_qualified_namespace: str, credential: TokenCredential | AzureSasCredential | AzureNamedKeyCredential, *, queue_name: str | None = None, topic_name: str | None = None, **kwargs: Any)[source]

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

Please use the `get_<queue/topic>_sender` method of ~azure.servicebus.ServiceBusClient to create a ServiceBusSender instance.

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 or AzureSasCredential or AzureNamedKeyCredential) – The credential object used for authentication which implements a particular interface for getting tokens. It accepts credential objects generated by the azure-identity library and objects that implement the get_token(self, *scopes) method, or alternatively, an AzureSasCredential can be provided too.

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.

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

  • user_agent (str) – If specified, this will be added in front of the built-in user agent string.

  • client_identifier (str) – A string-based identifier to uniquely identify the client instance. Service Bus will associate it with some error messages for easier correlation of errors. If not specified, a unique id will be generated.

  • socket_timeout (float) – The time in seconds that the underlying socket on the connection should wait when sending and receiving data before timing out. The default value is 0.2 for TransportType.Amqp and 1 for TransportType.AmqpOverWebsocket. If connection errors are occurring due to write timing out, a larger than default value may need to be passed in.

cancel_scheduled_messages(sequence_numbers: int | List[int], *, timeout: float | None = None, **kwargs: Any) None[source]

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

Parameters:

sequence_numbers (int or list[int]) – The sequence numbers of the scheduled messages.

Keyword Arguments:

timeout (float) – The total operation timeout in seconds including all the retries. The value must be greater than 0 if specified. The default value is None, meaning no timeout.

Return type:

None

Raises:

~azure.servicebus.exceptions.ServiceBusError if messages cancellation failed due to message already cancelled or enqueued.

Example:

Cancelling messages scheduled to be sent in future
with servicebus_sender:
    servicebus_sender.cancel_scheduled_messages(sequence_nums)
close() None

Close down the handler links (and connection if the handler uses a separate connection).

If the handler has already closed, this operation will do nothing.

Return type:

None

create_message_batch(max_size_in_bytes: int | None = None) ServiceBusMessageBatch[source]

Create a ServiceBusMessageBatch 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 (Optional[int]) – The maximum size of bytes data that a ServiceBusMessageBatch object can hold. By default, the value is determined by your Service Bus tier.

Returns:

A ServiceBusMessageBatch object

Return type:

ServiceBusMessageBatch

Example:

Create ServiceBusMessageBatch object within limited size
with servicebus_sender:
    batch_message = servicebus_sender.create_message_batch()
    batch_message.add_message(ServiceBusMessage("Single message inside batch"))
schedule_messages(messages: MessageTypes, schedule_time_utc: datetime, *, timeout: float | None = None, **kwargs: Any) List[int][source]

Send Message or multiple Messages to be enqueued at a specific time. Returns a list of the sequence numbers of the enqueued messages.

Parameters:
Keyword Arguments:

timeout (float) – The total operation timeout in seconds including all the retries. The value must be greater than 0 if specified. The default value is None, meaning no timeout.

Returns:

A list of the sequence numbers of the enqueued messages.

Return type:

list[int]

Example:

Schedule a message to be sent in future
with servicebus_sender:
    scheduled_time_utc = datetime.datetime.utcnow() + datetime.timedelta(seconds=30)
    scheduled_messages = [ServiceBusMessage("Scheduled message") for _ in range(10)]
    sequence_nums = servicebus_sender.schedule_messages(scheduled_messages, scheduled_time_utc)
send_messages(message: MessageTypes | ServiceBusMessageBatch, *, timeout: float | None = None, **kwargs: Any) None[source]

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

If a list of messages was provided, attempts to send them as a single batch, throwing a ValueError if they cannot fit in a single batch.

Parameters:

message (Union[ServiceBusMessage, ServiceBusMessageBatch, AmqpAnnotatedMessage, List[Union[ServiceBusMessage, AmqpAnnotatedMessage]]]) – The ServiceBus message to be sent.

Keyword Arguments:

timeout (Optional[float]) – The total operation timeout in seconds including all the retries. The value must be greater than 0 if specified. The default value is None, meaning no timeout.

Return type:

None

Raises:
class:

~azure.servicebus.exceptions.OperationTimeoutError if sending times out.

class:

~azure.servicebus.exceptions.MessageSizeExceededError if the size of the message is over service bus frame size limit.

class:

~azure.servicebus.exceptions.ServiceBusError when other errors happen such as connection error, authentication error, and any unexpected errors. It’s also the top-level root class of above errors.

Example:

Send message.
with servicebus_sender:
    message_send = ServiceBusMessage("Hello World")
    servicebus_sender.send_messages(message_send)
property client_identifier: str

Get the ServiceBusSender client_identifier associated with the sender instance.

Return type:

str

class azure.servicebus.ServiceBusSession(session_id: str, receiver: ServiceBusReceiver | ServiceBusReceiverAsync)[source]

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

Please use the property `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 AutoLockRenewer is used and it fails to renew the session lock.

Example:

Get session from a receiver
    with servicebus_client.get_queue_receiver(queue_name=queue_name, session_id=session_id) as receiver:
        session = receiver.session
get_state(*, timeout: float | None = None, **kwargs: Any) bytes[source]

Get the session state.

Returns None if no state has been set.

Keyword Arguments:

timeout (float) – The total operation timeout in seconds including all the retries. The value must be greater than 0 if specified. The default value is None, meaning no timeout.

Return type:

bytes

Returns:

The session state.

Example:

Get the session state
    with servicebus_client.get_queue_receiver(queue_name=queue_name, session_id=session_id) as receiver:
        session = receiver.session
        session_state = session.get_state()
renew_lock(*, timeout: float | None = None, **kwargs: Any) datetime[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; an expired lock cannot be renewed.

This operation can also be performed as a threaded background task by registering the session with an azure.servicebus.AutoLockRenewer instance.

Keyword Arguments:

timeout (float) – The total operation timeout in seconds including all the retries. The value must be greater than 0 if specified. The default value is None, meaning no timeout.

Returns:

The utc datetime the lock is set to expire at.

Return type:

datetime.datetime

Example:

Renew the session lock before it expires
    with servicebus_client.get_queue_receiver(queue_name=queue_name, session_id=session_id) as receiver:
        session = receiver.session
        session.renew_lock()
set_state(state: str | bytes | bytearray | None, *, timeout: float | None = None, **kwargs: Any) None[source]

Set the session state.

Parameters:

state (Union[str, bytes, bytearray, None]) – The state value. Setting state to None will clear the current session.

Keyword Arguments:

timeout (float) – The total operation timeout in seconds including all the retries. The value must be greater than 0 if specified. The default value is None, meaning no timeout.

Returns:

None

Return type:

None

Example:

Set the session state
    with servicebus_client.get_queue_receiver(queue_name=queue_name, session_id=session_id) as receiver:
        session = receiver.session
        session.set_state("START")
property locked_until_utc: datetime | None

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

Return type:

datetime.datetime

property session_id: str

Session id of the current session.

Return type:

str

class azure.servicebus.ServiceBusSessionFilter(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]
NEXT_AVAILABLE = 0
class azure.servicebus.ServiceBusSubQueue(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[source]
capitalize()

Return a capitalized version of the string.

More specifically, make the first character have upper case and the rest lower case.

casefold()

Return a version of the string suitable for caseless comparisons.

center(width, fillchar=' ', /)

Return a centered string of length width.

Padding is done using the specified fill character (default is a space).

count(sub[, start[, end]]) int

Return the number of non-overlapping occurrences of substring sub in string S[start:end]. Optional arguments start and end are interpreted as in slice notation.

encode(encoding='utf-8', errors='strict')

Encode the string using the codec registered for encoding.

encoding

The encoding in which to encode the string.

errors

The error handling scheme to use for encoding errors. The default is ‘strict’ meaning that encoding errors raise a UnicodeEncodeError. Other possible values are ‘ignore’, ‘replace’ and ‘xmlcharrefreplace’ as well as any other name registered with codecs.register_error that can handle UnicodeEncodeErrors.

endswith(suffix[, start[, end]]) bool

Return True if S ends with the specified suffix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. suffix can also be a tuple of strings to try.

expandtabs(tabsize=8)

Return a copy where all tab characters are expanded using spaces.

If tabsize is not given, a tab size of 8 characters is assumed.

find(sub[, start[, end]]) int

Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Return -1 on failure.

format(*args, **kwargs) str

Return a formatted version of S, using substitutions from args and kwargs. The substitutions are identified by braces (‘{’ and ‘}’).

format_map(mapping) str

Return a formatted version of S, using substitutions from mapping. The substitutions are identified by braces (‘{’ and ‘}’).

index(sub[, start[, end]]) int

Return the lowest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Raises ValueError when the substring is not found.

isalnum()

Return True if the string is an alpha-numeric string, False otherwise.

A string is alpha-numeric if all characters in the string are alpha-numeric and there is at least one character in the string.

isalpha()

Return True if the string is an alphabetic string, False otherwise.

A string is alphabetic if all characters in the string are alphabetic and there is at least one character in the string.

isascii()

Return True if all characters in the string are ASCII, False otherwise.

ASCII characters have code points in the range U+0000-U+007F. Empty string is ASCII too.

isdecimal()

Return True if the string is a decimal string, False otherwise.

A string is a decimal string if all characters in the string are decimal and there is at least one character in the string.

isdigit()

Return True if the string is a digit string, False otherwise.

A string is a digit string if all characters in the string are digits and there is at least one character in the string.

isidentifier()

Return True if the string is a valid Python identifier, False otherwise.

Call keyword.iskeyword(s) to test whether string s is a reserved identifier, such as “def” or “class”.

islower()

Return True if the string is a lowercase string, False otherwise.

A string is lowercase if all cased characters in the string are lowercase and there is at least one cased character in the string.

isnumeric()

Return True if the string is a numeric string, False otherwise.

A string is numeric if all characters in the string are numeric and there is at least one character in the string.

isprintable()

Return True if the string is printable, False otherwise.

A string is printable if all of its characters are considered printable in repr() or if it is empty.

isspace()

Return True if the string is a whitespace string, False otherwise.

A string is whitespace if all characters in the string are whitespace and there is at least one character in the string.

istitle()

Return True if the string is a title-cased string, False otherwise.

In a title-cased string, upper- and title-case characters may only follow uncased characters and lowercase characters only cased ones.

isupper()

Return True if the string is an uppercase string, False otherwise.

A string is uppercase if all cased characters in the string are uppercase and there is at least one cased character in the string.

join(iterable, /)

Concatenate any number of strings.

The string whose method is called is inserted in between each given string. The result is returned as a new string.

Example: ‘.’.join([‘ab’, ‘pq’, ‘rs’]) -> ‘ab.pq.rs’

ljust(width, fillchar=' ', /)

Return a left-justified string of length width.

Padding is done using the specified fill character (default is a space).

lower()

Return a copy of the string converted to lowercase.

lstrip(chars=None, /)

Return a copy of the string with leading whitespace removed.

If chars is given and not None, remove characters in chars instead.

static maketrans()

Return a translation table usable for str.translate().

If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters to Unicode ordinals, strings or None. Character keys will be then converted to ordinals. If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y. If there is a third argument, it must be a string, whose characters will be mapped to None in the result.

partition(sep, /)

Partition the string into three parts using the given separator.

This will search for the separator in the string. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.

If the separator is not found, returns a 3-tuple containing the original string and two empty strings.

removeprefix(prefix, /)

Return a str with the given prefix string removed if present.

If the string starts with the prefix string, return string[len(prefix):]. Otherwise, return a copy of the original string.

removesuffix(suffix, /)

Return a str with the given suffix string removed if present.

If the string ends with the suffix string and that suffix is not empty, return string[:-len(suffix)]. Otherwise, return a copy of the original string.

replace(old, new, count=-1, /)

Return a copy with all occurrences of substring old replaced by new.

count

Maximum number of occurrences to replace. -1 (the default value) means replace all occurrences.

If the optional argument count is given, only the first count occurrences are replaced.

rfind(sub[, start[, end]]) int

Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Return -1 on failure.

rindex(sub[, start[, end]]) int

Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation.

Raises ValueError when the substring is not found.

rjust(width, fillchar=' ', /)

Return a right-justified string of length width.

Padding is done using the specified fill character (default is a space).

rpartition(sep, /)

Partition the string into three parts using the given separator.

This will search for the separator in the string, starting at the end. If the separator is found, returns a 3-tuple containing the part before the separator, the separator itself, and the part after it.

If the separator is not found, returns a 3-tuple containing two empty strings and the original string.

rsplit(sep=None, maxsplit=-1)

Return a list of the substrings in the string, using sep as the separator string.

sep

The separator used to split the string.

When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.

maxsplit

Maximum number of splits. -1 (the default value) means no limit.

Splitting starts at the end of the string and works to the front.

rstrip(chars=None, /)

Return a copy of the string with trailing whitespace removed.

If chars is given and not None, remove characters in chars instead.

split(sep=None, maxsplit=-1)

Return a list of the substrings in the string, using sep as the separator string.

sep

The separator used to split the string.

When set to None (the default value), will split on any whitespace character (including n r t f and spaces) and will discard empty strings from the result.

maxsplit

Maximum number of splits. -1 (the default value) means no limit.

Splitting starts at the front of the string and works to the end.

Note, str.split() is mainly useful for data that has been intentionally delimited. With natural text that includes punctuation, consider using the regular expression module.

splitlines(keepends=False)

Return a list of the lines in the string, breaking at line boundaries.

Line breaks are not included in the resulting list unless keepends is given and true.

startswith(prefix[, start[, end]]) bool

Return True if S starts with the specified prefix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. prefix can also be a tuple of strings to try.

strip(chars=None, /)

Return a copy of the string with leading and trailing whitespace removed.

If chars is given and not None, remove characters in chars instead.

swapcase()

Convert uppercase characters to lowercase and lowercase characters to uppercase.

title()

Return a version of the string where each word is titlecased.

More specifically, words start with uppercased characters and all remaining cased characters have lower case.

translate(table, /)

Replace each character in the string using the given translation table.

table

Translation table, which must be a mapping of Unicode ordinals to Unicode ordinals, strings, or None.

The table must implement lookup/indexing via __getitem__, for instance a dictionary or list. If this operation raises LookupError, the character is left untouched. Characters mapped to None are deleted.

upper()

Return a copy of the string converted to uppercase.

zfill(width, /)

Pad a numeric string with zeros on the left, to fill a field of the given width.

The string is never truncated.

DEAD_LETTER = 'deadletter'
TRANSFER_DEAD_LETTER = 'transferdeadletter'
class azure.servicebus.TransportType(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)[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
azure.servicebus.parse_connection_string(conn_str: str) ServiceBusConnectionStringProperties[source]

Parse the connection string into a properties bag containing its component parts.

Parameters:

conn_str (str) – The connection string that has to be parsed.

Returns:

A properties model containing the parsed connection string.

Return type:

ServiceBusConnectionStringProperties

Subpackages

Submodules

azure.servicebus.exceptions module

exception azure.servicebus.exceptions.AutoLockRenewFailed(message: str | bytes | None, *args: Any, **kwargs: Any)[source]

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

add_note()

Exception.add_note(note) – add a note to the exception

raise_with_traceback() None

Raise the exception with the existing traceback.

Deprecated since version 1.22.0: This method is deprecated as we don’t support Python 2 anymore. Use raise/from instead.

with_traceback()

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

args
exception azure.servicebus.exceptions.AutoLockRenewTimeout(message: str | bytes | None, *args: Any, **kwargs: Any)[source]

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

add_note()

Exception.add_note(note) – add a note to the exception

raise_with_traceback() None

Raise the exception with the existing traceback.

Deprecated since version 1.22.0: This method is deprecated as we don’t support Python 2 anymore. Use raise/from instead.

with_traceback()

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

args
exception azure.servicebus.exceptions.MessageAlreadySettled(**kwargs: Any)[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).

add_note()

Exception.add_note(note) – add a note to the exception

with_traceback()

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

args
exception azure.servicebus.exceptions.MessageLockLostError(**kwargs: Any)[source]

The lock on the message is lost. Callers should call attempt to receive and process the message again.

add_note()

Exception.add_note(note) – add a note to the exception

raise_with_traceback() None

Raise the exception with the existing traceback.

Deprecated since version 1.22.0: This method is deprecated as we don’t support Python 2 anymore. Use raise/from instead.

with_traceback()

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

args
exception azure.servicebus.exceptions.MessageNotFoundError(**kwargs: Any)[source]

The requested message was not found.

Attempt to receive a message with a particular sequence number. This message isn’t found. Make sure the message hasn’t been received already. Check the deadletter queue to see if the message has been deadlettered.

add_note()

Exception.add_note(note) – add a note to the exception

raise_with_traceback() None

Raise the exception with the existing traceback.

Deprecated since version 1.22.0: This method is deprecated as we don’t support Python 2 anymore. Use raise/from instead.

with_traceback()

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

args
exception azure.servicebus.exceptions.MessageSizeExceededError(**kwargs: Any)[source]

Message content is larger than the service bus frame size.

add_note()

Exception.add_note(note) – add a note to the exception

raise_with_traceback() None

Raise the exception with the existing traceback.

Deprecated since version 1.22.0: This method is deprecated as we don’t support Python 2 anymore. Use raise/from instead.

with_traceback()

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

args
exception azure.servicebus.exceptions.MessagingEntityAlreadyExistsError(**kwargs: Any)[source]

An entity with the same name exists under the same namespace.

add_note()

Exception.add_note(note) – add a note to the exception

raise_with_traceback() None

Raise the exception with the existing traceback.

Deprecated since version 1.22.0: This method is deprecated as we don’t support Python 2 anymore. Use raise/from instead.

with_traceback()

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

args
exception azure.servicebus.exceptions.MessagingEntityDisabledError(**kwargs: Any)[source]

The Messaging Entity is disabled. Enable the entity again using Portal.

add_note()

Exception.add_note(note) – add a note to the exception

raise_with_traceback() None

Raise the exception with the existing traceback.

Deprecated since version 1.22.0: This method is deprecated as we don’t support Python 2 anymore. Use raise/from instead.

with_traceback()

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

args
exception azure.servicebus.exceptions.MessagingEntityNotFoundError(**kwargs: Any)[source]

A Service Bus resource cannot be found by the Service Bus service.

Entity associated with the operation doesn’t exist or it has been deleted. Please make sure the entity exists.

add_note()

Exception.add_note(note) – add a note to the exception

raise_with_traceback() None

Raise the exception with the existing traceback.

Deprecated since version 1.22.0: This method is deprecated as we don’t support Python 2 anymore. Use raise/from instead.

with_traceback()

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

args
exception azure.servicebus.exceptions.OperationTimeoutError(**kwargs: Any)[source]

Operation timed out.

add_note()

Exception.add_note(note) – add a note to the exception

raise_with_traceback() None

Raise the exception with the existing traceback.

Deprecated since version 1.22.0: This method is deprecated as we don’t support Python 2 anymore. Use raise/from instead.

with_traceback()

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

args
exception azure.servicebus.exceptions.ServiceBusAuthenticationError(**kwargs: Any)[source]

An error occurred when authenticate the connection.

add_note()

Exception.add_note(note) – add a note to the exception

raise_with_traceback() None

Raise the exception with the existing traceback.

Deprecated since version 1.22.0: This method is deprecated as we don’t support Python 2 anymore. Use raise/from instead.

with_traceback()

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

args
exception azure.servicebus.exceptions.ServiceBusAuthorizationError(**kwargs: Any)[source]

An error occurred when authorizing the connection.

add_note()

Exception.add_note(note) – add a note to the exception

raise_with_traceback() None

Raise the exception with the existing traceback.

Deprecated since version 1.22.0: This method is deprecated as we don’t support Python 2 anymore. Use raise/from instead.

with_traceback()

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

args
exception azure.servicebus.exceptions.ServiceBusCommunicationError(**kwargs: Any)[source]

There was a general communications error encountered when interacting with the Azure Service Bus service.

Client isn’t able to establish a connection to Service Bus. Make sure the supplied host name is correct and the host is reachable. If your code runs in an environment with a firewall/proxy, ensure that the traffic to the Service Bus domain/IP address and ports isn’t blocked.

add_note()

Exception.add_note(note) – add a note to the exception

raise_with_traceback() None

Raise the exception with the existing traceback.

Deprecated since version 1.22.0: This method is deprecated as we don’t support Python 2 anymore. Use raise/from instead.

with_traceback()

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

args
exception azure.servicebus.exceptions.ServiceBusConnectionError(**kwargs: Any)[source]

An error occurred in the connection.

add_note()

Exception.add_note(note) – add a note to the exception

raise_with_traceback() None

Raise the exception with the existing traceback.

Deprecated since version 1.22.0: This method is deprecated as we don’t support Python 2 anymore. Use raise/from instead.

with_traceback()

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

args
exception azure.servicebus.exceptions.ServiceBusError(message: str | bytes | None, *args: Any, **kwargs: Any)[source]

Base exception for all Service Bus errors which can be used for default error handling.

Parameters:

message (str or bytes) – The message object stringified as ‘message’ attribute

Keyword Arguments:

error (Exception) – The original exception if any

Variables:
  • exc_type – The exc_type from sys.exc_info()

  • exc_value – The exc_value from sys.exc_info()

  • exc_traceback – The exc_traceback from sys.exc_info()

  • exc_msg – A string formatting of message parameter, exc_type and exc_value

  • message (str) – A stringified version of the message parameter

add_note()

Exception.add_note(note) – add a note to the exception

raise_with_traceback() None

Raise the exception with the existing traceback.

Deprecated since version 1.22.0: This method is deprecated as we don’t support Python 2 anymore. Use raise/from instead.

with_traceback()

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

args
exception azure.servicebus.exceptions.ServiceBusQuotaExceededError(**kwargs: Any)[source]

The quota applied to a Service Bus resource has been exceeded while interacting with the Azure Service Bus service.

The messaging entity has reached its maximum allowable size, or the maximum number of connections to a namespace has been exceeded. Create space in the entity by receiving messages from the entity or its subqueues.

add_note()

Exception.add_note(note) – add a note to the exception

raise_with_traceback() None

Raise the exception with the existing traceback.

Deprecated since version 1.22.0: This method is deprecated as we don’t support Python 2 anymore. Use raise/from instead.

with_traceback()

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

args
continuation_token: str | None
exc_msg: str
exc_traceback: TracebackType | None
exc_type: Type[Any] | None
exc_value: BaseException | None
inner_exception: BaseException | None
message: str
exception azure.servicebus.exceptions.ServiceBusServerBusyError(**kwargs: Any)[source]

The Azure Service Bus service reports that it is busy in response to a client request to perform an operation.

Service isn’t able to process the request at this time. Client can wait for a period of time, then retry the operation.

add_note()

Exception.add_note(note) – add a note to the exception

raise_with_traceback() None

Raise the exception with the existing traceback.

Deprecated since version 1.22.0: This method is deprecated as we don’t support Python 2 anymore. Use raise/from instead.

with_traceback()

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

args
continuation_token: str | None
exc_msg: str
exc_traceback: TracebackType | None
exc_type: Type[Any] | None
exc_value: BaseException | None
inner_exception: BaseException | None
message: str
exception azure.servicebus.exceptions.SessionCannotBeLockedError(**kwargs: Any)[source]

The requested session cannot be locked.

Attempt to connect to a session with a specific session ID, but the session is currently locked by another client. Make sure the session is unlocked by other clients.

add_note()

Exception.add_note(note) – add a note to the exception

raise_with_traceback() None

Raise the exception with the existing traceback.

Deprecated since version 1.22.0: This method is deprecated as we don’t support Python 2 anymore. Use raise/from instead.

with_traceback()

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

args
continuation_token: str | None
exc_msg: str
exc_traceback: TracebackType | None
exc_type: Type[Any] | None
exc_value: BaseException | None
inner_exception: BaseException | None
message: str
exception azure.servicebus.exceptions.SessionLockLostError(**kwargs: Any)[source]

The lock on the session has expired. Callers should request the session again.

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

add_note()

Exception.add_note(note) – add a note to the exception

raise_with_traceback() None

Raise the exception with the existing traceback.

Deprecated since version 1.22.0: This method is deprecated as we don’t support Python 2 anymore. Use raise/from instead.

with_traceback()

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

args
continuation_token: str | None
exc_msg: str
exc_traceback: TracebackType | None
exc_type: Type[Any] | None
exc_value: BaseException | None
inner_exception: BaseException | None
message: str