def list_by_workspace(<EOL>self, resource_group_name, workspace_name, experiments_list_by_workspace_options=None, custom_headers=None, raw=False, **operation_config):

max_results = None<EOL>if experiments_list_by_workspace_options is not None:<EOL><INDENT>max_results = experiments_list_by_workspace_options.max_results<EOL><DEDENT>def internal_paging(next_link=None, raw=False):<EOL><INDENT>if not next_link:<EOL><INDENT>url = self.list_by_workspace.metadata['<STR_LIT:url>']<EOL>path_format_arguments = {<EOL>'<STR_LIT>': self._serialize.url("<STR_LIT>", resource_group_name, '<STR_LIT:str>', pattern=r'<STR_LIT>'),<EOL>'<STR_LIT>': self._serialize.url("<STR_LIT>", workspace_name, '<STR_LIT:str>', max_length=<NUM_LIT:64>, min_length=<NUM_LIT:1>, pattern=r'<STR_LIT>'),<EOL>'<STR_LIT>': self._serialize.url("<STR_LIT>", self.config.subscription_id, '<STR_LIT:str>')<EOL>}<EOL>url = self._client.format_url(url, **path_format_arguments)<EOL>query_parameters = {}<EOL>query_parameters['<STR_LIT>'] = self._serialize.query("<STR_LIT>", self.api_version, '<STR_LIT:str>')<EOL>if max_results is not None:<EOL><INDENT>query_parameters['<STR_LIT>'] = self._serialize.query("<STR_LIT>", max_results, '<STR_LIT:int>', maximum=<NUM_LIT:1000>, minimum=<NUM_LIT:1>)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>url = next_link<EOL>query_parameters = {}<EOL><DEDENT>header_parameters = {}<EOL>header_parameters['<STR_LIT:Content-Type>'] = '<STR_LIT>'<EOL>if self.config.generate_client_request_id:<EOL><INDENT>header_parameters['<STR_LIT>'] = str(uuid.uuid1())<EOL><DEDENT>if custom_headers:<EOL><INDENT>header_parameters.update(custom_headers)<EOL><DEDENT>if self.config.accept_language is not None:<EOL><INDENT>header_parameters['<STR_LIT>'] = self._serialize.header("<STR_LIT>", self.config.accept_language, '<STR_LIT:str>')<EOL><DEDENT>request = self._client.get(url, query_parameters)<EOL>response = self._client.send(<EOL>request, header_parameters, stream=False, **operation_config)<EOL>if response.status_code not in [<NUM_LIT:200>]:<EOL><INDENT>exp = CloudError(response)<EOL>exp.request_id = response.headers.get('<STR_LIT>')<EOL>raise exp<EOL><DEDENT>return response<EOL><DEDENT>deserialized = models.ExperimentPaged(internal_paging, self._deserialize.dependencies)<EOL>if raw:<EOL><INDENT>header_dict = {}<EOL>client_raw_response = models.ExperimentPaged(internal_paging, self._deserialize.dependencies, header_dict)<EOL>return client_raw_response<EOL><DEDENT>return deserialized<EOL>

Gets a list of Experiments within the specified Workspace.

        :param resource_group_name: Name of the resource group to which the
         resource belongs.
        :type resource_group_name: str
        :param workspace_name: The name of the workspace. Workspace names can
         only contain a combination of alphanumeric characters along with dash
         (-) and underscore (_). The name must be from 1 through 64 characters
         long.
        :type workspace_name: str
        :param experiments_list_by_workspace_options: Additional parameters
         for the operation
        :type experiments_list_by_workspace_options:
         ~azure.mgmt.batchai.models.ExperimentsListByWorkspaceOptions
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: An iterator like instance of Experiment
        :rtype:
         ~azure.mgmt.batchai.models.ExperimentPaged[~azure.mgmt.batchai.models.Experiment]
        :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`


def create(<EOL>self, resource_group_name, workspace_name, experiment_name, custom_headers=None, raw=False, polling=True, **operation_config):

raw_result = self._create_initial(<EOL>resource_group_name=resource_group_name,<EOL>workspace_name=workspace_name,<EOL>experiment_name=experiment_name,<EOL>custom_headers=custom_headers,<EOL>raw=True,<EOL>**operation_config<EOL>)<EOL>def get_long_running_output(response):<EOL><INDENT>deserialized = self._deserialize('<STR_LIT>', response)<EOL>if raw:<EOL><INDENT>client_raw_response = ClientRawResponse(deserialized, response)<EOL>return client_raw_response<EOL><DEDENT>return deserialized<EOL><DEDENT>lro_delay = operation_config.get(<EOL>'<STR_LIT>',<EOL>self.config.long_running_operation_timeout)<EOL>if polling is True: polling_method = ARMPolling(lro_delay, **operation_config)<EOL>elif polling is False: polling_method = NoPolling()<EOL>else: polling_method = polling<EOL>return LROPoller(self._client, raw_result, get_long_running_output, polling_method)<EOL>

Creates an Experiment.

        :param resource_group_name: Name of the resource group to which the
         resource belongs.
        :type resource_group_name: str
        :param workspace_name: The name of the workspace. Workspace names can
         only contain a combination of alphanumeric characters along with dash
         (-) and underscore (_). The name must be from 1 through 64 characters
         long.
        :type workspace_name: str
        :param experiment_name: The name of the experiment. Experiment names
         can only contain a combination of alphanumeric characters along with
         dash (-) and underscore (_). The name must be from 1 through 64
         characters long.
        :type experiment_name: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: The poller return type is ClientRawResponse, the
         direct response alongside the deserialized response
        :param polling: True for ARMPolling, False for no polling, or a
         polling object for personal polling strategy
        :return: An instance of LROPoller that returns Experiment or
         ClientRawResponse<Experiment> if raw==True
        :rtype:
         ~msrestazure.azure_operation.AzureOperationPoller[~azure.mgmt.batchai.models.Experiment]
         or
         ~msrestazure.azure_operation.AzureOperationPoller[~msrest.pipeline.ClientRawResponse[~azure.mgmt.batchai.models.Experiment]]
        :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`


def delete(<EOL>self, resource_group_name, workspace_name, experiment_name, custom_headers=None, raw=False, polling=True, **operation_config):

raw_result = self._delete_initial(<EOL>resource_group_name=resource_group_name,<EOL>workspace_name=workspace_name,<EOL>experiment_name=experiment_name,<EOL>custom_headers=custom_headers,<EOL>raw=True,<EOL>**operation_config<EOL>)<EOL>def get_long_running_output(response):<EOL><INDENT>if raw:<EOL><INDENT>client_raw_response = ClientRawResponse(None, response)<EOL>return client_raw_response<EOL><DEDENT><DEDENT>lro_delay = operation_config.get(<EOL>'<STR_LIT>',<EOL>self.config.long_running_operation_timeout)<EOL>if polling is True: polling_method = ARMPolling(lro_delay, **operation_config)<EOL>elif polling is False: polling_method = NoPolling()<EOL>else: polling_method = polling<EOL>return LROPoller(self._client, raw_result, get_long_running_output, polling_method)<EOL>

Deletes an Experiment.

        :param resource_group_name: Name of the resource group to which the
         resource belongs.
        :type resource_group_name: str
        :param workspace_name: The name of the workspace. Workspace names can
         only contain a combination of alphanumeric characters along with dash
         (-) and underscore (_). The name must be from 1 through 64 characters
         long.
        :type workspace_name: str
        :param experiment_name: The name of the experiment. Experiment names
         can only contain a combination of alphanumeric characters along with
         dash (-) and underscore (_). The name must be from 1 through 64
         characters long.
        :type experiment_name: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: The poller return type is ClientRawResponse, the
         direct response alongside the deserialized response
        :param polling: True for ARMPolling, False for no polling, or a
         polling object for personal polling strategy
        :return: An instance of LROPoller that returns None or
         ClientRawResponse<None> if raw==True
        :rtype: ~msrestazure.azure_operation.AzureOperationPoller[None] or
         ~msrestazure.azure_operation.AzureOperationPoller[~msrest.pipeline.ClientRawResponse[None]]
        :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`


def get(<EOL>self, resource_group_name, workspace_name, experiment_name, custom_headers=None, raw=False, **operation_config):

<EOL>url = self.get.metadata['<STR_LIT:url>']<EOL>path_format_arguments = {<EOL>'<STR_LIT>': self._serialize.url("<STR_LIT>", resource_group_name, '<STR_LIT:str>', pattern=r'<STR_LIT>'),<EOL>'<STR_LIT>': self._serialize.url("<STR_LIT>", workspace_name, '<STR_LIT:str>', max_length=<NUM_LIT:64>, min_length=<NUM_LIT:1>, pattern=r'<STR_LIT>'),<EOL>'<STR_LIT>': self._serialize.url("<STR_LIT>", experiment_name, '<STR_LIT:str>', max_length=<NUM_LIT:64>, min_length=<NUM_LIT:1>, pattern=r'<STR_LIT>'),<EOL>'<STR_LIT>': self._serialize.url("<STR_LIT>", self.config.subscription_id, '<STR_LIT:str>')<EOL>}<EOL>url = self._client.format_url(url, **path_format_arguments)<EOL>query_parameters = {}<EOL>query_parameters['<STR_LIT>'] = self._serialize.query("<STR_LIT>", self.api_version, '<STR_LIT:str>')<EOL>header_parameters = {}<EOL>header_parameters['<STR_LIT:Content-Type>'] = '<STR_LIT>'<EOL>if self.config.generate_client_request_id:<EOL><INDENT>header_parameters['<STR_LIT>'] = str(uuid.uuid1())<EOL><DEDENT>if custom_headers:<EOL><INDENT>header_parameters.update(custom_headers)<EOL><DEDENT>if self.config.accept_language is not None:<EOL><INDENT>header_parameters['<STR_LIT>'] = self._serialize.header("<STR_LIT>", self.config.accept_language, '<STR_LIT:str>')<EOL><DEDENT>request = self._client.get(url, query_parameters)<EOL>response = self._client.send(request, header_parameters, stream=False, **operation_config)<EOL>if response.status_code not in [<NUM_LIT:200>]:<EOL><INDENT>exp = CloudError(response)<EOL>exp.request_id = response.headers.get('<STR_LIT>')<EOL>raise exp<EOL><DEDENT>deserialized = None<EOL>if response.status_code == <NUM_LIT:200>:<EOL><INDENT>deserialized = self._deserialize('<STR_LIT>', response)<EOL><DEDENT>if raw:<EOL><INDENT>client_raw_response = ClientRawResponse(deserialized, response)<EOL>return client_raw_response<EOL><DEDENT>return deserialized<EOL>

Gets information about an Experiment.

        :param resource_group_name: Name of the resource group to which the
         resource belongs.
        :type resource_group_name: str
        :param workspace_name: The name of the workspace. Workspace names can
         only contain a combination of alphanumeric characters along with dash
         (-) and underscore (_). The name must be from 1 through 64 characters
         long.
        :type workspace_name: str
        :param experiment_name: The name of the experiment. Experiment names
         can only contain a combination of alphanumeric characters along with
         dash (-) and underscore (_). The name must be from 1 through 64
         characters long.
        :type experiment_name: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: Experiment or ClientRawResponse if raw=true
        :rtype: ~azure.mgmt.batchai.models.Experiment or
         ~msrest.pipeline.ClientRawResponse
        :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`


def list(<EOL>self, location, custom_headers=None, raw=False, **operation_config):

def internal_paging(next_link=None, raw=False):<EOL><INDENT>if not next_link:<EOL><INDENT>url = self.list.metadata['<STR_LIT:url>']<EOL>path_format_arguments = {<EOL>'<STR_LIT>': self._serialize.url("<STR_LIT>", self.config.subscription_id, '<STR_LIT:str>'),<EOL>'<STR_LIT:location>': self._serialize.url("<STR_LIT:location>", location, '<STR_LIT:str>', pattern=r'<STR_LIT>')<EOL>}<EOL>url = self._client.format_url(url, **path_format_arguments)<EOL>query_parameters = {}<EOL>query_parameters['<STR_LIT>'] = self._serialize.query("<STR_LIT>", self.api_version, '<STR_LIT:str>')<EOL><DEDENT>else:<EOL><INDENT>url = next_link<EOL>query_parameters = {}<EOL><DEDENT>header_parameters = {}<EOL>header_parameters['<STR_LIT:Content-Type>'] = '<STR_LIT>'<EOL>if self.config.generate_client_request_id:<EOL><INDENT>header_parameters['<STR_LIT>'] = str(uuid.uuid1())<EOL><DEDENT>if custom_headers:<EOL><INDENT>header_parameters.update(custom_headers)<EOL><DEDENT>if self.config.accept_language is not None:<EOL><INDENT>header_parameters['<STR_LIT>'] = self._serialize.header("<STR_LIT>", self.config.accept_language, '<STR_LIT:str>')<EOL><DEDENT>request = self._client.get(url, query_parameters)<EOL>response = self._client.send(<EOL>request, header_parameters, stream=False, **operation_config)<EOL>if response.status_code not in [<NUM_LIT:200>]:<EOL><INDENT>exp = CloudError(response)<EOL>exp.request_id = response.headers.get('<STR_LIT>')<EOL>raise exp<EOL><DEDENT>return response<EOL><DEDENT>deserialized = models.UsagePaged(internal_paging, self._deserialize.dependencies)<EOL>if raw:<EOL><INDENT>header_dict = {}<EOL>client_raw_response = models.UsagePaged(internal_paging, self._deserialize.dependencies, header_dict)<EOL>return client_raw_response<EOL><DEDENT>return deserialized<EOL>

Gets the current usage information as well as limits for Batch AI
        resources for given subscription.

        :param location: The location for which resource usage is queried.
        :type location: str
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: An iterator like instance of Usage
        :rtype:
         ~azure.mgmt.batchai.models.UsagePaged[~azure.mgmt.batchai.models.Usage]
        :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>`


This is a temporary patch pending a fix in uAMQP.


<EOL>if self._handler._received_messages:<EOL><INDENT>return self._handler._received_messages.qsize()<EOL><DEDENT>return <NUM_LIT:0><EOL>

The current size of the unprocessed message queue.

        :rtype: int

        Example:
            .. literalinclude:: ../examples/test_examples.py
                :start-after: [START queue_size]
                :end-before: [END queue_size]
                :language: python
                :dedent: 4
                :caption: Get the number of unprocessed messages in the queue


def peek(self, count=<NUM_LIT:1>, start_from=None):

if not start_from:<EOL><INDENT>start_from = self.last_received or <NUM_LIT:1><EOL><DEDENT>if int(count) < <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if int(start_from) < <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>self._can_run()<EOL>message = {<EOL>'<STR_LIT>': types.AMQPLong(start_from),<EOL>'<STR_LIT>': count<EOL>}<EOL>return self._mgmt_request_response(<EOL>REQUEST_RESPONSE_PEEK_OPERATION,<EOL>message,<EOL>mgmt_handlers.peek_op)<EOL>

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.

        :param count: The maximum number of messages to try and peek. The default
         value is 1.
        :type count: int
        :param start_from: A message sequence number from which to start browsing messages.
        :type start_from: int
        :rtype: list[~azure.servicebus.common.message.PeekMessage]

        Example:
            .. literalinclude:: ../examples/test_examples.py
                :start-after: [START peek_messages]
                :end-before: [END peek_messages]
                :language: python
                :dedent: 4
                :caption: Look at pending messages in the queue


def receive_deferred_messages(self, sequence_numbers, mode=ReceiveSettleMode.PeekLock):

if not sequence_numbers:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>self._can_run()<EOL>try:<EOL><INDENT>receive_mode = mode.value.value<EOL><DEDENT>except AttributeError:<EOL><INDENT>receive_mode = int(mode)<EOL><DEDENT>message = {<EOL>'<STR_LIT>': types.AMQPArray([types.AMQPLong(s) for s in sequence_numbers]),<EOL>'<STR_LIT>': types.AMQPuInt(receive_mode)<EOL>}<EOL>handler = functools.partial(mgmt_handlers.deferred_message_op, mode=receive_mode)<EOL>messages = self._mgmt_request_response(<EOL>REQUEST_RESPONSE_RECEIVE_BY_SEQUENCE_NUMBER,<EOL>message,<EOL>handler)<EOL>for m in messages:<EOL><INDENT>m._receiver = self  <EOL><DEDENT>return messages<EOL>

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.

        :param sequence_numbers: A list of the sequence numbers of messages that have been
         deferred.
        :type sequence_numbers: list[int]
        :param mode: The receive mode, default value is PeekLock.
        :type mode: ~azure.servicebus.common.constants.ReceiveSettleMode
        :rtype: list[~azure.servicebus.common.message.DeferredMessage]

        Example:
            .. literalinclude:: ../examples/test_examples.py
                :start-after: [START receive_deferred_messages]
                :end-before: [END receive_deferred_messages]
                :language: python
                :dedent: 8
                :caption: Get the messages which were previously deferred


if self.running:<EOL><INDENT>return<EOL><DEDENT>self.running = True<EOL>try:<EOL><INDENT>self._handler.open(connection=self.connection)<EOL>self.message_iter = self._handler.receive_messages_iter()<EOL>while not self._handler.auth_complete():<EOL><INDENT>time.sleep(<NUM_LIT>)<EOL><DEDENT>self._build_receiver()<EOL>while not self._handler.client_ready():<EOL><INDENT>time.sleep(<NUM_LIT>)<EOL><DEDENT><DEDENT>except Exception as e:  <EOL><INDENT>try:<EOL><INDENT>self._handle_exception(e)<EOL><DEDENT>except:<EOL><INDENT>self.running = False<EOL>raise<EOL><DEDENT><DEDENT>

Open receiver connection and authenticate session.

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

        .. note:: This operation is not thread-safe.


if not self.running:<EOL><INDENT>return<EOL><DEDENT>self.running = False<EOL>self.receiver_shutdown = True<EOL>self._used.set()<EOL>super(Receiver, self).close(exception=exception)<EOL>

Close down the receiver connection.

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

        .. note:: This operation is not thread-safe.

        :param exception: An optional exception if the handler is closing
         due to an error.
        :type exception: Exception

        Example:
            .. literalinclude:: ../examples/test_examples.py
                :start-after: [START open_close_receiver_connection]
                :end-before: [END open_close_receiver_connection]
                :language: python
                :dedent: 4
                :caption: Close the connection and shutdown the receiver


def fetch_next(self, max_batch_size=None, timeout=None):

self._can_run()<EOL>wrapped_batch = []<EOL>max_batch_size = max_batch_size or self._handler._prefetch  <EOL>try:<EOL><INDENT>timeout_ms = <NUM_LIT:1000> * timeout if timeout else <NUM_LIT:0><EOL>batch = self._handler.receive_message_batch(<EOL>max_batch_size=max_batch_size,<EOL>timeout=timeout_ms)<EOL>for received in batch:<EOL><INDENT>message = self._build_message(received)<EOL>wrapped_batch.append(message)<EOL><DEDENT><DEDENT>except Exception as e:  <EOL><INDENT>self._handle_exception(e)<EOL><DEDENT>return wrapped_batch<EOL>

Receive a batch of messages at once.

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

        :param max_batch_size: Maximum number of messages in the batch. Actual number
         returned will depend on prefetch size and incoming stream rate.
        :type max_batch_size: int
        :param timeout: The time to wait in seconds for the first message to arrive.
         If no messages arrive, and no timeout is specified, this call will not return
         until the connection is closed. If specified, an no messages arrive within the
         timeout period, an empty list will be returned.
        :rtype: list[~azure.servicebus.common.message.Message]

        Example:
            .. literalinclude:: ../examples/test_examples.py
                :start-after: [START fetch_next_messages]
                :end-before: [END fetch_next_messages]
                :language: python
                :dedent: 4
                :caption: Get the messages in batch from the receiver


self._can_run()<EOL>response = self._mgmt_request_response(<EOL>REQUEST_RESPONSE_GET_SESSION_STATE_OPERATION,<EOL>{'<STR_LIT>': self.session_id},<EOL>mgmt_handlers.default)<EOL>session_state = response.get(b'<STR_LIT>')<EOL>if isinstance(session_state, six.binary_type):<EOL><INDENT>session_state = session_state.decode('<STR_LIT>')<EOL><DEDENT>return session_state<EOL>

Get the session state.

        Returns None if no state has been set.

        :rtype: str

        Example:
            .. literalinclude:: ../examples/test_examples.py
                :start-after: [START get_session_state]
                :end-before: [END get_session_state]
                :language: python
                :dedent: 4
                :caption: Get the session state of the receiver


self._can_run()<EOL>state = state.encode(self.encoding) if isinstance(state, six.text_type) else state<EOL>return self._mgmt_request_response(<EOL>REQUEST_RESPONSE_SET_SESSION_STATE_OPERATION,<EOL>{'<STR_LIT>': self.session_id, '<STR_LIT>': bytearray(state)},<EOL>mgmt_handlers.default)<EOL>

Set the session state.

        :param state: The state value.
        :type state: str, bytes or bytearray

        Example:
            .. literalinclude:: ../examples/test_examples.py
                :start-after: [START set_session_state]
                :end-before: [END set_session_state]
                :language: python
                :dedent: 4
                :caption: Set the session state of the receiver


self._can_run()<EOL>expiry = self._mgmt_request_response(<EOL>REQUEST_RESPONSE_RENEW_SESSION_LOCK_OPERATION,<EOL>{'<STR_LIT>': self.session_id},<EOL>mgmt_handlers.default)<EOL>self.locked_until = datetime.datetime.fromtimestamp(expiry[b'<STR_LIT>']/<NUM_LIT>)<EOL>

Renew the session lock.

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

        Example:
            .. literalinclude:: ../examples/test_examples.py
                :start-after: [START renew_lock]
                :end-before: [END renew_lock]
                :language: python
                :dedent: 4
                :caption: Renew the session lock before it expires


if not start_from:<EOL><INDENT>start_from = self.last_received or <NUM_LIT:1><EOL><DEDENT>if int(count) < <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if int(start_from) < <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>self._can_run()<EOL>message = {<EOL>'<STR_LIT>': types.AMQPLong(start_from),<EOL>'<STR_LIT>': count,<EOL>'<STR_LIT>': self.session_id}<EOL>return self._mgmt_request_response(<EOL>REQUEST_RESPONSE_PEEK_OPERATION,<EOL>message,<EOL>mgmt_handlers.peek_op)<EOL>

Browse messages currently pending in the queue.

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

        :param count: The maximum number of messages to try and peek. The default
         value is 1.
        :type count: int
        :param start_from: A message sequence number from which to start browsing messages.
        :type start_from: int
        :rtype: list[~azure.servicebus.common.message.PeekMessage]

        Example:
            .. literalinclude:: ../examples/test_examples.py
                :start-after: [START peek_messages]
                :end-before: [END peek_messages]
                :language: python
                :dedent: 4
                :caption: Look at pending messages in the queue


if not sequence_numbers:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>self._can_run()<EOL>try:<EOL><INDENT>receive_mode = mode.value.value<EOL><DEDENT>except AttributeError:<EOL><INDENT>receive_mode = int(mode)<EOL><DEDENT>message = {<EOL>'<STR_LIT>': types.AMQPArray([types.AMQPLong(s) for s in sequence_numbers]),<EOL>'<STR_LIT>': types.AMQPuInt(receive_mode),<EOL>'<STR_LIT>': self.session_id<EOL>}<EOL>handler = functools.partial(mgmt_handlers.deferred_message_op, mode=receive_mode)<EOL>messages = self._mgmt_request_response(<EOL>REQUEST_RESPONSE_RECEIVE_BY_SEQUENCE_NUMBER,<EOL>message,<EOL>handler)<EOL>for m in messages:<EOL><INDENT>m._receiver = self  <EOL><DEDENT>return messages<EOL>

Receive messages that have previously been deferred.

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

        :param sequence_numbers: A list of the sequence numbers of messages that have been
         deferred.
        :type sequence_numbers: list[int]
        :param mode: The receive mode, default value is PeekLock.
        :type mode: ~azure.servicebus.common.constants.ReceiveSettleMode
        :rtype: list[~azure.servicebus.common.message.DeferredMessage]

        Example:
            .. literalinclude:: ../examples/test_examples.py
                :start-after: [START receive_deferred_messages]
                :end-before: [END receive_deferred_messages]
                :language: python
                :dedent: 4
                :caption: Get the messages which were previously deferred in the session


def list_sessions(self, updated_since=None, max_results=<NUM_LIT:100>, skip=<NUM_LIT:0>):

if int(max_results) < <NUM_LIT:1>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>self._can_run()<EOL>message = {<EOL>'<STR_LIT>': updated_since or datetime.datetime.utcfromtimestamp(<NUM_LIT:0>),<EOL>'<STR_LIT>': skip,<EOL>'<STR_LIT>': max_results,<EOL>}<EOL>return self._mgmt_request_response(<EOL>REQUEST_RESPONSE_GET_MESSAGE_SESSIONS_OPERATION,<EOL>message,<EOL>mgmt_handlers.list_sessions_op)<EOL>

List session IDs.

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

        :param updated_since: The UTC datetime from which to return updated pending Session IDs.
        :type updated_since: datetime.datetime
        :param max_results: The maximum number of Session IDs to return. Default value is 100.
        :type max_results: int
        :param skip: The page value to jump to. Default value is 0.
        :type skip: int
        :rtype: list[str]

        Example:
            .. literalinclude:: ../examples/test_examples.py
                :start-after: [START list_sessions]
                :end-before: [END list_sessions]
                :language: python
                :dedent: 4
                :caption: List the ids of sessions with pending messages


self.open()<EOL>return self<EOL>


self.close()<EOL>

Close the handler when exiting a context manager.


self._handler.close()<EOL>self._build_handler()<EOL>self.open()<EOL>

Reconnect the handler.

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


if self.running:<EOL><INDENT>return<EOL><DEDENT>self.running = True<EOL>try:<EOL><INDENT>self._handler.open(connection=self.connection)<EOL>while not self._handler.client_ready():<EOL><INDENT>time.sleep(<NUM_LIT>)<EOL><DEDENT><DEDENT>except Exception as e:  <EOL><INDENT>try:<EOL><INDENT>self._handle_exception(e)<EOL><DEDENT>except:<EOL><INDENT>self.running = False<EOL>raise<EOL><DEDENT><DEDENT>

Open handler connection and authenticate session.

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

        .. note:: This operation is not thread-safe.


self.running = False<EOL>if self.error:<EOL><INDENT>return<EOL><DEDENT>if isinstance(exception, ServiceBusError):<EOL><INDENT>self.error = exception<EOL><DEDENT>elif exception:<EOL><INDENT>self.error = ServiceBusError(str(exception))<EOL><DEDENT>else:<EOL><INDENT>self.error = ServiceBusError("<STR_LIT>")<EOL><DEDENT>self._handler.close()<EOL>

Close down the handler connection.

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

        .. note:: This operation is not thread-safe.

        :param exception: An optional exception if the handler is closing
         due to an error.
        :type exception: Exception


@classmethod<EOL><INDENT>def from_connection_string(cls, conn_str, **kwargs):<DEDENT>

address, policy, key, _ = parse_conn_str(conn_str)<EOL>parsed_namespace = urlparse(address)<EOL>namespace, _, base = parsed_namespace.hostname.partition('<STR_LIT:.>')<EOL>return cls(<EOL>namespace,<EOL>shared_access_key_name=policy,<EOL>shared_access_key_value=key,<EOL>host_base='<STR_LIT:.>' + base,<EOL>**kwargs)<EOL>

Create a Service Bus client from a connection string.

        :param conn_str: The connection string.
        :type conn_str: str

        Example:
            .. literalinclude:: ../examples/test_examples.py
                :start-after: [START create_servicebus_client_connstr]
                :end-before: [END create_servicebus_client_connstr]
                :language: python
                :dedent: 4
                :caption: Create a ServiceBusClient via a connection string.


try:<EOL><INDENT>queue = self.mgmt_client.get_queue(queue_name)<EOL><DEDENT>except requests.exceptions.ConnectionError as e:<EOL><INDENT>raise ServiceBusConnectionError("<STR_LIT>".format(self.service_namespace), e)<EOL><DEDENT>except AzureServiceBusResourceNotFound:<EOL><INDENT>raise ServiceBusResourceNotFound("<STR_LIT>")<EOL><DEDENT>return QueueClient.from_entity(<EOL>self._get_host(), queue,<EOL>shared_access_key_name=self.shared_access_key_name,<EOL>shared_access_key_value=self.shared_access_key_value,<EOL>mgmt_client=self.mgmt_client,<EOL>debug=self.debug)<EOL>

Get a client for a queue entity.

        :param queue_name: The name of the queue.
        :type queue_name: str
        :rtype: ~azure.servicebus.servicebus_client.QueueClient
        :raises: ~azure.servicebus.common.errors.ServiceBusConnectionError if the namespace is not found.
        :raises: ~azure.servicebus.common.errors.ServiceBusResourceNotFound if the queue is not found.

        Example:
            .. literalinclude:: ../examples/test_examples.py
                :start-after: [START get_queue_client]
                :end-before: [END get_queue_client]
                :language: python
                :dedent: 8
                :caption: Get the specific queue client from Service Bus client


try:<EOL><INDENT>queues = self.mgmt_client.list_queues()<EOL><DEDENT>except requests.exceptions.ConnectionError as e:<EOL><INDENT>raise ServiceBusConnectionError("<STR_LIT>".format(self.service_namespace), e)<EOL><DEDENT>queue_clients = []<EOL>for queue in queues:<EOL><INDENT>queue_clients.append(QueueClient.from_entity(<EOL>self._get_host(), queue,<EOL>shared_access_key_name=self.shared_access_key_name,<EOL>shared_access_key_value=self.shared_access_key_value,<EOL>mgmt_client=self.mgmt_client,<EOL>debug=self.debug))<EOL><DEDENT>return queue_clients<EOL>

Get clients for all queue entities in the namespace.

        :rtype: list[~azure.servicebus.servicebus_client.QueueClient]
        :raises: ~azure.servicebus.common.errors.ServiceBusConnectionError if the namespace is not found.

        Example:
            .. literalinclude:: ../examples/test_examples.py
                :start-after: [START list_queues]
                :end-before: [END list_queues]
                :language: python
                :dedent: 4
                :caption: List the queues from Service Bus client


try:<EOL><INDENT>topic = self.mgmt_client.get_topic(topic_name)<EOL><DEDENT>except requests.exceptions.ConnectionError as e:<EOL><INDENT>raise ServiceBusConnectionError("<STR_LIT>".format(self.service_namespace), e)<EOL><DEDENT>except AzureServiceBusResourceNotFound:<EOL><INDENT>raise ServiceBusResourceNotFound("<STR_LIT>")<EOL><DEDENT>return TopicClient.from_entity(<EOL>self._get_host(), topic,<EOL>shared_access_key_name=self.shared_access_key_name,<EOL>shared_access_key_value=self.shared_access_key_value,<EOL>debug=self.debug)<EOL>

Get a client for a topic entity.

        :param topic_name: The name of the topic.
        :type topic_name: str
        :rtype: ~azure.servicebus.servicebus_client.TopicClient
        :raises: ~azure.servicebus.common.errors.ServiceBusConnectionError if the namespace is not found.
        :raises: ~azure.servicebus.common.errors.ServiceBusResourceNotFound if the topic is not found.

        Example:
            .. literalinclude:: ../examples/test_examples.py
                :start-after: [START get_topic_client]
                :end-before: [END get_topic_client]
                :language: python
                :dedent: 8
                :caption: Get the specific topic client from Service Bus client


try:<EOL><INDENT>topics = self.mgmt_client.list_topics()<EOL><DEDENT>except requests.exceptions.ConnectionError as e:<EOL><INDENT>raise ServiceBusConnectionError("<STR_LIT>".format(self.service_namespace), e)<EOL><DEDENT>topic_clients = []<EOL>for topic in topics:<EOL><INDENT>topic_clients.append(TopicClient.from_entity(<EOL>self._get_host(), topic,<EOL>shared_access_key_name=self.shared_access_key_name,<EOL>shared_access_key_value=self.shared_access_key_value,<EOL>debug=self.debug))<EOL><DEDENT>return topic_clients<EOL>

Get a client for all topic entities in the namespace.

        :rtype: list[~azure.servicebus.servicebus_client.TopicClient]
        :raises: ~azure.servicebus.common.errors.ServiceBusConnectionError if the namespace is not found.

        Example:
            .. literalinclude:: ../examples/test_examples.py
                :start-after: [START list_topics]
                :end-before: [END list_topics]
                :language: python
                :dedent: 4
                :caption: List the topics from Service Bus client


def get_subscription(self, topic_name, subscription_name):

try:<EOL><INDENT>subscription = self.mgmt_client.get_subscription(topic_name, subscription_name)<EOL><DEDENT>except requests.exceptions.ConnectionError as e:<EOL><INDENT>raise ServiceBusConnectionError("<STR_LIT>".format(self.service_namespace), e)<EOL><DEDENT>except AzureServiceBusResourceNotFound:<EOL><INDENT>raise ServiceBusResourceNotFound("<STR_LIT>")<EOL><DEDENT>return SubscriptionClient.from_entity(<EOL>self._get_host(), topic_name, subscription,<EOL>shared_access_key_name=self.shared_access_key_name,<EOL>shared_access_key_value=self.shared_access_key_value,<EOL>debug=self.debug)<EOL>

Get a client for a subscription entity.

        :param topic_name: The name of the topic.
        :type topic_name: str
        :param subscription_name: The name of the subscription.
        :type subscription_name: str
        :rtype: ~azure.servicebus.servicebus_client.SubscriptionClient
        :raises: ~azure.servicebus.common.errors.ServiceBusConnectionError if the namespace is not found.
        :raises: ~azure.servicebus.common.errors.ServiceBusResourceNotFound if the subscription is not found.

        Example:
            .. literalinclude:: ../examples/test_examples.py
                :start-after: [START get_subscription_client]
                :end-before: [END get_subscription_client]
                :language: python
                :dedent: 8
                :caption: Get the specific subscription client from Service Bus client


try:<EOL><INDENT>subs = self.mgmt_client.list_subscriptions(topic_name)<EOL><DEDENT>except requests.exceptions.ConnectionError as e:<EOL><INDENT>raise ServiceBusConnectionError("<STR_LIT>".format(self.service_namespace), e)<EOL><DEDENT>except AzureServiceBusResourceNotFound:<EOL><INDENT>raise ServiceBusResourceNotFound("<STR_LIT>")<EOL><DEDENT>sub_clients = []<EOL>for sub in subs:<EOL><INDENT>sub_clients.append(SubscriptionClient.from_entity(<EOL>self._get_host(), topic_name, sub,<EOL>shared_access_key_name=self.shared_access_key_name,<EOL>shared_access_key_value=self.shared_access_key_value,<EOL>debug=self.debug))<EOL><DEDENT>return sub_clients<EOL>

Get a client for all subscription entities in the topic.

        :param topic_name: The topic to list subscriptions for.
        :type topic_name: str
        :rtype: list[~azure.servicebus.servicebus_client.SubscriptionClient]
        :raises: ~azure.servicebus.common.errors.ServiceBusConnectionError if the namespace is not found.
        :raises: ~azure.servicebus.common.errors.ServiceBusResourceNotFound if the topic is not found.

        Example:
            .. literalinclude:: ../examples/test_examples.py
                :start-after: [START list_subscriptions]
                :end-before: [END list_subscriptions]
                :language: python
                :dedent: 4
                :caption: List the subscriptions from Service Bus client


def send(self, messages, message_timeout=<NUM_LIT:0>, session=None, **kwargs):

with self.get_sender(message_timeout=message_timeout, session=session, **kwargs) as sender:<EOL><INDENT>if isinstance(messages, Message):<EOL><INDENT>sender.queue_message(messages)<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>messages = list(messages)<EOL><DEDENT>except TypeError:<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>for m in messages:<EOL><INDENT>if not isinstance(m, Message):<EOL><INDENT>raise TypeError("<STR_LIT>".format(m))<EOL><DEDENT>sender.queue_message(m)<EOL><DEDENT><DEDENT>return sender.send_pending_messages()<EOL><DEDENT>

Send one or more messages to the current entity.

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

        :param messages: One or more messages to be sent.
        :type messages: ~azure.servicebus.common.message.Message or list[~azure.servicebus.common.message.Message]
        :param message_timeout: The period in seconds during which the Message must be
         sent. If the send is not completed in this time it will return a failure result.
        :type message_timeout: int
        :param session: An optional session ID. If supplied this session ID will be
         applied to every outgoing message sent with this Sender.
         If an individual message already has a session ID, that will be
         used instead. If no session ID is supplied here, nor set on an outgoing
         message, a ValueError will be raised if the entity is sessionful.
        :type session: str or ~uuid.Guid
        :raises: ~azure.servicebus.common.errors.MessageSendFailed
        :returns: A list of the send results of all the messages. Each
         send result is a tuple with two values. The first is a boolean, indicating `True`
         if the message sent, or `False` if it failed. The second is an error if the message
         failed, otherwise it will be `None`.
        :rtype: list[tuple[bool, ~azure.servicebus.common.errors.MessageSendFailed]]

        Example:
            .. literalinclude:: ../examples/test_examples.py
                :start-after: [START send_message_service_bus]
                :end-before: [END send_message_service_bus]
                :language: python
                :dedent: 4
                :caption: Send a message to current entity via a single use connection

            .. literalinclude:: ../examples/test_examples.py
                :start-after: [START send_message_service_bus_multiple]
                :end-before: [END send_message_service_bus_multiple]
                :language: python
                :dedent: 4
                :caption: Send messages to current entity via a single use connection


def get_sender(self, message_timeout=<NUM_LIT:0>, session=None, **kwargs):

Get a Sender for the Service Bus endpoint.

        A Sender represents a single open Connection with which multiple send operations can be made.

        :param message_timeout: The period in seconds during which messages sent with
         this Sender must be sent. If the send is not completed in this time it will fail.
        :type message_timeout: int
        :param session: An optional session ID. If supplied this session ID will be
         applied to every outgoing message sent with this Sender.
         If an individual message already has a session ID, that will be
         used instead. If no session ID is supplied here, nor set on an outgoing
         message, a ValueError will be raised if the entity is sessionful.
        :type session: str or ~uuid.Guid
        :returns: A Sender instance with an unopened connection.
        :rtype: ~azure.servicebus.send_handler.Sender

        Example:
            .. literalinclude:: ../examples/test_examples.py
                :start-after: [START get_sender]
                :end-before: [END get_sender]
                :language: python
                :dedent: 4
                :caption: Get sender client from Service Bus client


def peek(self, count=<NUM_LIT:1>, start_from=<NUM_LIT:0>, session=None, **kwargs):

message = {'<STR_LIT>': types.AMQPLong(start_from), '<STR_LIT>': int(count)}<EOL>if self.entity and self.requires_session:<EOL><INDENT>if not session:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>message['<STR_LIT>'] = session<EOL><DEDENT>with BaseHandler(self.entity_uri, self.auth_config, debug=self.debug, **kwargs) as handler:<EOL><INDENT>return handler._mgmt_request_response(  <EOL>REQUEST_RESPONSE_PEEK_OPERATION,<EOL>message,<EOL>mgmt_handlers.peek_op)<EOL><DEDENT>

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.

        :param count: The maximum number of messages to try and peek. The default
         value is 1.
        :type count: int
        :param start_from: A message sequence number from which to start browsing messages.
        :type start_from: int
        :param session: If the entity requires sessions, a session ID must be supplied
         in order that only messages from that session will be browsed. If the entity
         does not require sessions this value will be ignored.
        :type session: str
        :rtype: list[~azure.servicebus.common.message.PeekMessage]

        Example:
            .. literalinclude:: ../examples/test_examples.py
                :start-after: [START peek_messages_service_bus]
                :end-before: [END peek_messages_service_bus]
                :language: python
                :dedent: 4
                :caption: Look at specificied number of messages without removing them from queue


def list_sessions(self, updated_since=None, max_results=<NUM_LIT:100>, skip=<NUM_LIT:0>, **kwargs):

if self.entity and not self.requires_session:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>message = {<EOL>'<STR_LIT>': updated_since or datetime.datetime.utcfromtimestamp(<NUM_LIT:0>),<EOL>'<STR_LIT>': types.AMQPInt(skip),<EOL>'<STR_LIT>': types.AMQPInt(max_results),<EOL>}<EOL>with BaseHandler(self.entity_uri, self.auth_config, debug=self.debug, **kwargs) as handler:<EOL><INDENT>return handler._mgmt_request_response(  <EOL>REQUEST_RESPONSE_GET_MESSAGE_SESSIONS_OPERATION,<EOL>message,<EOL>mgmt_handlers.list_sessions_op)<EOL><DEDENT>

List session IDs.

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

        :param updated_since: The UTC datetime from which to return updated pending Session IDs.
        :type updated_since: datetime.datetime
        :param max_results: The maximum number of Session IDs to return. Default value is 100.
        :type max_results: int
        :param skip: The page value to jump to. Default value is 0.
        :type skip: int
        :rtype: list[str]

        Example:
            .. literalinclude:: ../examples/test_examples.py
                :start-after: [START list_sessions_service_bus]
                :end-before: [END list_sessions_service_bus]
                :language: python
                :dedent: 4
                :caption: Get the Ids of session which have messages pending in the queue


def receive_deferred_messages(self, sequence_numbers, mode=ReceiveSettleMode.PeekLock, **kwargs):

if (self.entity and self.requires_session) or kwargs.get('<STR_LIT>'):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if not sequence_numbers:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>try:<EOL><INDENT>receive_mode = mode.value.value<EOL><DEDENT>except AttributeError:<EOL><INDENT>receive_mode = int(mode)<EOL><DEDENT>message = {<EOL>'<STR_LIT>': types.AMQPArray([types.AMQPLong(s) for s in sequence_numbers]),<EOL>'<STR_LIT>': types.AMQPuInt(receive_mode)}<EOL>mgmt_handler = functools.partial(mgmt_handlers.deferred_message_op, mode=receive_mode)<EOL>with BaseHandler(self.entity_uri, self.auth_config, debug=self.debug, **kwargs) as handler:<EOL><INDENT>return handler._mgmt_request_response(  <EOL>REQUEST_RESPONSE_RECEIVE_BY_SEQUENCE_NUMBER,<EOL>message,<EOL>mgmt_handler)<EOL><DEDENT>

Receive messages by sequence number that have been previously deferred.

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

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

        Example:
            .. literalinclude:: ../examples/test_examples.py
                :start-after: [START receive_deferred_messages_service_bus]
                :end-before: [END receive_deferred_messages_service_bus]
                :language: python
                :dedent: 8
                :caption: Get the messages which were deferred using their sequence numbers


def settle_deferred_messages(self, settlement, messages, **kwargs):

if (self.entity and self.requires_session) or kwargs.get('<STR_LIT>'):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if settlement.lower() not in ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if not messages:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>message = {<EOL>'<STR_LIT>': settlement.lower(),<EOL>'<STR_LIT>': types.AMQPArray([m.lock_token for m in messages])}<EOL>with BaseHandler(self.entity_uri, self.auth_config, debug=self.debug, **kwargs) as handler:<EOL><INDENT>return handler._mgmt_request_response(  <EOL>REQUEST_RESPONSE_UPDATE_DISPOSTION_OPERATION,<EOL>message,<EOL>mgmt_handlers.default)<EOL><DEDENT>

Settle messages that have been previously deferred.

        :param settlement: How the messages are to be settled. This must be a string
         of one of the following values: 'completed', 'suspended', 'abandoned'.
        :type settlement: str
        :param messages: A list of deferred messages to be settled.
        :type messages: list[~azure.servicebus.common.message.DeferredMessage]

        Example:
            .. literalinclude:: ../examples/test_examples.py
                :start-after: [START settle_deferred_messages_service_bus]
                :end-before: [END settle_deferred_messages_service_bus]
                :language: python
                :dedent: 8
                :caption: Settle deferred messages.


def get_receiver(self, session=None, prefetch=<NUM_LIT:0>, mode=ReceiveSettleMode.PeekLock, idle_timeout=<NUM_LIT:0>, **kwargs):

if self.entity and not self.requires_session and session:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if self.entity and self.requires_session and not session:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if int(prefetch) < <NUM_LIT:0> or int(prefetch) > <NUM_LIT>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>prefetch += <NUM_LIT:1><EOL>handler_id = str(uuid.uuid4())<EOL>if session:<EOL><INDENT>return SessionReceiver(<EOL>handler_id,<EOL>self.entity_uri,<EOL>self.auth_config,<EOL>session=session,<EOL>debug=self.debug,<EOL>timeout=int(idle_timeout * <NUM_LIT:1000>),<EOL>prefetch=prefetch,<EOL>mode=mode,<EOL>**kwargs)<EOL><DEDENT>return Receiver(<EOL>handler_id,<EOL>self.entity_uri,<EOL>self.auth_config,<EOL>debug=self.debug,<EOL>timeout=int(idle_timeout * <NUM_LIT:1000>),<EOL>prefetch=prefetch,<EOL>mode=mode,<EOL>**kwargs)<EOL>

Get a Receiver for the Service Bus endpoint.

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

        :param session: A specific session from which to receive. This must be specified for a
         sessionful entity, otherwise it must be None. In order to receive the next available
         session, set this to NEXT_AVAILABLE.
        :type session: str or ~azure.servicebus.common.constants.NEXT_AVAILABLE
        :param prefetch: The maximum number of messages to cache with each request to the service.
         The default value is 0, meaning messages will be received from the service and processed
         one at a time. Increasing this value will improve message throughput performance but increase
         the change that messages will expire while they are cached if they're not processed fast enough.
        :type prefetch: int
        :param mode: The mode with which messages will be retrieved from the entity. The two options
         are PeekLock and ReceiveAndDelete. Messages received with PeekLock must be settled within a given
         lock period before they will be removed from the queue. Messages received with ReceiveAndDelete
         will be immediately removed from the queue, and cannot be subsequently rejected or re-received if
         the client fails to process the message. The default mode is PeekLock.
        :type mode: ~azure.servicebus.common.constants.ReceiveSettleMode
        :param idle_timeout: The timeout in seconds between received messages after which the receiver will
         automatically shutdown. The default value is 0, meaning no timeout.
        :type idle_timeout: int
        :returns: A Receiver instance with an unopened Connection.
        :rtype: ~azure.servicebus.receive_handler.Receiver
        :raises: If the current Service Bus entity requires sessions, a TypeError will
         be raised.

        Example:
            .. literalinclude:: ../examples/test_examples.py
                :start-after: [START get_receiver]
                :end-before: [END get_receiver]
                :language: python
                :dedent: 4
                :caption: Get the receiver client from Service Bus client


def get_deadletter_receiver(<EOL>self, transfer_deadletter=False, prefetch=<NUM_LIT:0>,<EOL>mode=ReceiveSettleMode.PeekLock, idle_timeout=<NUM_LIT:0>, **kwargs):

if int(prefetch) < <NUM_LIT:0> or int(prefetch) > <NUM_LIT>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>prefetch += <NUM_LIT:1><EOL>handler_id = str(uuid.uuid4())<EOL>if transfer_deadletter:<EOL><INDENT>entity_uri = self.mgmt_client.format_transfer_dead_letter_queue_name(self.entity_uri)<EOL><DEDENT>else:<EOL><INDENT>entity_uri = self.mgmt_client.format_dead_letter_queue_name(self.entity_uri)<EOL><DEDENT>return Receiver(<EOL>handler_id,<EOL>entity_uri,<EOL>self.auth_config,<EOL>debug=self.debug,<EOL>timeout=int(idle_timeout * <NUM_LIT:1000>),<EOL>prefetch=prefetch,<EOL>mode=mode,<EOL>**kwargs)<EOL>

Get a Receiver for the deadletter endpoint of the queue.

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

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

        Example:
            .. literalinclude:: ../examples/test_examples.py
                :start-after: [START get_dead_letter_receiver]
                :end-before: [END get_dead_letter_receiver]
                :language: python
                :dedent: 4
                :caption: Get the dead lettered messages


@classmethod<EOL><INDENT>def from_connection_string(cls, conn_str, name, topic=None, **kwargs):  <DEDENT>

address, policy, key, entity = parse_conn_str(conn_str)<EOL>entity = topic or entity<EOL>address = build_uri(address, entity)<EOL>address += "<STR_LIT>" + name<EOL>return cls(address, name, shared_access_key_name=policy, shared_access_key_value=key, **kwargs)<EOL>

Create a SubscriptionClient from a connection string.

        :param conn_str: The connection string.
        :type conn_str: str
        :param name: The name of the Subscription.
        :type name: str
        :param topic: The name of the Topic, if the EntityName is
         not included in the connection string.
        :type topic: str


if not isinstance(message, Message):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>if not self.running:<EOL><INDENT>await self.open()<EOL><DEDENT>if self.session_id and not message.properties.group_id:<EOL><INDENT>message.properties.group_id = self.session_id<EOL><DEDENT>try:<EOL><INDENT>await self._handler.send_message_async(message.message)<EOL><DEDENT>except Exception as e:  <EOL><INDENT>raise MessageSendFailed(e)<EOL><DEDENT>

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

        :param message: The message to be sent.
        :type message: ~azure.servicebus.aio.async_message.Message
        :raises: ~azure.servicebus.common.errors.MessageSendFailed if the message fails to
         send.

        Example:
            .. literalinclude:: ../examples/async_examples/test_examples_async.py
                :start-after: [START open_close_sender_context]
                :end-before: [END open_close_sender_context]
                :language: python
                :dedent: 4
                :caption: Open a Sender and send messages.


async def schedule(self, schedule_time, *messages):

if not self.running:<EOL><INDENT>await self.open()<EOL><DEDENT>request_body = self._build_schedule_request(schedule_time, *messages)<EOL>return await self._mgmt_request_response(<EOL>REQUEST_RESPONSE_SCHEDULE_MESSAGE_OPERATION,<EOL>request_body,<EOL>mgmt_handlers.schedule_op)<EOL>

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

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

        :param schedule_time: The date and time to enqueue the messages.
        :type schedule_time: ~datetime.datetime
        :param messages: The messages to schedule.
        :type messages: ~azure.servicebus.aio.async_message.Message
        :rtype: list[int]

        Example:
            .. literalinclude:: ../examples/async_examples/test_examples_async.py
                :start-after: [START schedule_messages]
                :end-before: [END schedule_messages]
                :language: python
                :dedent: 4
                :caption: Schedule messages.


async def cancel_scheduled_messages(self, *sequence_numbers):

if not self.running:<EOL><INDENT>await self.open()<EOL><DEDENT>numbers = [types.AMQPLong(s) for s in sequence_numbers]<EOL>request_body = {'<STR_LIT>': types.AMQPArray(numbers)}<EOL>return await self._mgmt_request_response(<EOL>REQUEST_RESPONSE_CANCEL_SCHEDULED_MESSAGE_OPERATION,<EOL>request_body,<EOL>mgmt_handlers.default)<EOL>

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

        :param sequence_numbers: The seqeuence numbers of the scheduled messages.
        :type sequence_numbers: int

        Example:
            .. literalinclude:: ../examples/async_examples/test_examples_async.py
                :start-after: [START cancel_schedule_messages]
                :end-before: [END cancel_schedule_messages]
                :language: python
                :dedent: 4
                :caption: Schedule messages.


if not self.running:<EOL><INDENT>await self.open()<EOL><DEDENT>try:<EOL><INDENT>pending = self._handler._pending_messages[:]  <EOL>await self._handler.wait_async()<EOL>results = []<EOL>for m in pending:<EOL><INDENT>if m.state == constants.MessageState.SendFailed:<EOL><INDENT>results.append((False, MessageSendFailed(m._response)))  <EOL><DEDENT>else:<EOL><INDENT>results.append((True, None))<EOL><DEDENT><DEDENT>return results<EOL><DEDENT>except Exception as e:  <EOL><INDENT>raise MessageSendFailed(e)<EOL><DEDENT>

Wait until all pending messages have been sent.

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

        Example:
            .. literalinclude:: ../examples/async_examples/test_examples_async.py
                :start-after: [START queue_sender_messages]
                :end-before: [END queue_sender_messages]
                :language: python
                :dedent: 4
                :caption: Schedule messages.


unsent_events = self._handler.pending_messages<EOL>await super(Sender, self).reconnect()<EOL>try:<EOL><INDENT>self._handler.queue_message(*unsent_events)<EOL>await self._handler.wait_async()<EOL><DEDENT>except Exception as e:  <EOL><INDENT>await self._handle_exception(e)<EOL><DEDENT>

Reconnect the handler.

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


if not isinstance(message, Message):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>if not self.session_id and not message.properties.group_id:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>return await super(SessionSender, self).send(message)<EOL>

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

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

        :param message: The message to be sent.
        :type message: ~azure.servicebus.aio.async_message.Message
        :raises: ~azure.servicebus.common.errors.MessageSendFailed if the message fails to
         send.

        Example:
            .. literalinclude:: ../examples/async_examples/test_examples_async.py
                :start-after: [START open_close_session_sender_context]
                :end-before: [END open_close_session_sender_context]
                :language: python
                :dedent: 4
                :caption: Open a sessionful Sender and send messages.


if not self.session_id and not message.properties.group_id:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>super(SessionSender, self).queue_message(message)<EOL>

Queue a message to be sent later.

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

        :param message: The message to be sent.
        :type message: ~azure.servicebus.aio.async_message.Message

        Example:
            .. literalinclude:: ../examples/async_examples/test_examples_async.py
                :start-after: [START queue_session_sender_messages]
                :end-before: [END queue_session_sender_messages]
                :language: python
                :dedent: 4
                :caption: Schedule messages.


async def schedule_messages(self, schedule_time, *messages):

for message in messages:<EOL><INDENT>if not self.session_id and not message.properties.group_id:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT><DEDENT>return await super(SessionSender, self).schedule(schedule_time, *messages)<EOL>

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

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

        :param schedule_time: The date and time to enqueue the messages.
        :type schedule_time: ~datetime.datetime
        :param messages: The messages to schedule.
        :type messages: ~azure.servicebus.aio.async_message.Message
        :rtype: list[int]

        Example:
            .. literalinclude:: ../examples/async_examples/test_examples_async.py
                :start-after: [START schedule_session_messages]
                :end-before: [END schedule_session_messages]
                :language: python
                :dedent: 4
                :caption: Schedule messages.


if hasattr(self._receiver, '<STR_LIT>'):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>self._is_live('<STR_LIT>')<EOL>expiry = await self._receiver._renew_locks(self.lock_token)  <EOL>self._expiry = datetime.datetime.fromtimestamp(expiry[b'<STR_LIT>'][<NUM_LIT:0>]/<NUM_LIT>)<EOL>

Renew the message lock.

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

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


self._is_live('<STR_LIT>')<EOL>try:<EOL><INDENT>await self._loop.run_in_executor(None, self.message.accept)<EOL><DEDENT>except Exception as e:<EOL><INDENT>raise MessageSettleFailed("<STR_LIT>", e)<EOL><DEDENT>

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

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


async def dead_letter(self, description=None):

self._is_live('<STR_LIT>')<EOL>try:<EOL><INDENT>reject = functools.partial(self.message.reject, condition=DEADLETTERNAME, description=description)<EOL>await self._loop.run_in_executor(None, reject)<EOL><DEDENT>except Exception as e:<EOL><INDENT>raise MessageSettleFailed("<STR_LIT>", e)<EOL><DEDENT>

Move the message to the Dead Letter queue.

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

        :param description: The reason for dead-lettering the message.
        :type description: str
        :raises: ~azure.servicebus.common.errors.MessageAlreadySettled if the message has been settled.
        :raises: ~azure.servicebus.common.errors.MessageLockExpired if message lock has already expired.
        :raises: ~azure.servicebus.common.errors.SessionLockExpired if session lock has already expired.
        :raises: ~azure.servicebus.common.errors.MessageSettleFailed if message settle operation fails.


self._is_live('<STR_LIT>')<EOL>try:<EOL><INDENT>modify = functools.partial(self.message.modify, True, False)<EOL>await self._loop.run_in_executor(None, modify)<EOL><DEDENT>except Exception as e:<EOL><INDENT>raise MessageSettleFailed("<STR_LIT>", e)<EOL><DEDENT>

Abandon the message.

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

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


self._is_live('<STR_LIT>')<EOL>try:<EOL><INDENT>modify = functools.partial(self.message.modify, True, True)<EOL>await self._loop.run_in_executor(None, modify)<EOL><DEDENT>except Exception as e:<EOL><INDENT>raise MessageSettleFailed("<STR_LIT>", e)<EOL><DEDENT>

Defer the message.

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

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


self._is_live('<STR_LIT>')<EOL>await self._receiver._settle_deferred('<STR_LIT>', [self.lock_token])  <EOL>self._settled = True<EOL>

Complete the message.

        This removes the message from the queue.

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


self._is_live('<STR_LIT>')<EOL>details = {<EOL>'<STR_LIT>': str(description) if description else "<STR_LIT>",<EOL>'<STR_LIT>': str(description) if description else "<STR_LIT>"}<EOL>await self._receiver._settle_deferred(  <EOL>'<STR_LIT>', [self.lock_token], dead_letter_details=details)<EOL>self._settled = True<EOL>

Move the message to the Dead Letter queue.

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

        :param description: The reason for dead-lettering the message.
        :type description: str
        :raises: ~azure.servicebus.common.errors.MessageAlreadySettled if the message has been settled.
        :raises: ~azure.servicebus.common.errors.MessageLockExpired if message lock has already expired.
        :raises: ~azure.servicebus.common.errors.MessageSettleFailed if message settle operation fails.


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

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


raise ValueError("<STR_LIT>")<EOL>

A DeferredMessage cannot be deferred. Raises `ValueError`.


@classmethod<EOL><INDENT>def from_connection_string(cls, conn_str, *, loop=None, **kwargs):<DEDENT>

address, policy, key, _ = parse_conn_str(conn_str)<EOL>parsed_namespace = urlparse(address)<EOL>namespace, _, base = parsed_namespace.hostname.partition('<STR_LIT:.>')<EOL>return cls(<EOL>service_namespace=namespace,<EOL>shared_access_key_name=policy,<EOL>shared_access_key_value=key,<EOL>host_base='<STR_LIT:.>' + base,<EOL>loop=loop,<EOL>**kwargs)<EOL>

Create a Service Bus client from a connection string.

        :param conn_str: The connection string.
        :type conn_str: str

        Example:
            .. literalinclude:: ../examples/async_examples/test_examples_async.py
                :start-after: [START create_async_servicebus_client_connstr]
                :end-before: [END create_async_servicebus_client_connstr]
                :language: python
                :dedent: 4
                :caption: Create a ServiceBusClient via a connection string.


try:<EOL><INDENT>queue = self.mgmt_client.get_queue(queue_name)<EOL><DEDENT>except requests.exceptions.ConnectionError as e:<EOL><INDENT>raise ServiceBusConnectionError("<STR_LIT>".format(self.service_namespace), e)<EOL><DEDENT>except AzureServiceBusResourceNotFound:<EOL><INDENT>raise ServiceBusResourceNotFound("<STR_LIT>")<EOL><DEDENT>return QueueClient.from_entity(<EOL>self._get_host(), queue,<EOL>shared_access_key_name=self.shared_access_key_name,<EOL>shared_access_key_value=self.shared_access_key_value,<EOL>mgmt_client=self.mgmt_client,<EOL>loop=self.loop,<EOL>debug=self.debug)<EOL>

Get an async client for a queue entity.

        :param queue_name: The name of the queue.
        :type queue_name: str
        :rtype: ~azure.servicebus.aio.async_client.QueueClient
        :raises: ~azure.servicebus.common.errors.ServiceBusConnectionError if the namespace is not found.
        :raises: ~azure.servicebus.common.errors.ServiceBusResourceNotFound if the queue is not found.

        Example:
            .. literalinclude:: ../examples/async_examples/test_examples_async.py
                :start-after: [START get_async_queue_client]
                :end-before: [END get_async_queue_client]
                :language: python
                :dedent: 4
                :caption: Get a QueueClient for the specified queue.


try:<EOL><INDENT>queues = self.mgmt_client.list_queues()<EOL><DEDENT>except requests.exceptions.ConnectionError as e:<EOL><INDENT>raise ServiceBusConnectionError("<STR_LIT>".format(self.service_namespace), e)<EOL><DEDENT>queue_clients = []<EOL>for queue in queues:<EOL><INDENT>queue_clients.append(QueueClient.from_entity(<EOL>self._get_host(), queue,<EOL>shared_access_key_name=self.shared_access_key_name,<EOL>shared_access_key_value=self.shared_access_key_value,<EOL>mgmt_client=self.mgmt_client,<EOL>loop=self.loop,<EOL>debug=self.debug))<EOL><DEDENT>return queue_clients<EOL>

Get async clients for all queue entities in the namespace.

        :rtype: list[~azure.servicebus.aio.async_client.QueueClient]
        :raises: ~azure.servicebus.common.errors.ServiceBusConnectionError if the namespace is not found.


try:<EOL><INDENT>topic = self.mgmt_client.get_topic(topic_name)<EOL><DEDENT>except requests.exceptions.ConnectionError as e:<EOL><INDENT>raise ServiceBusConnectionError("<STR_LIT>".format(self.service_namespace), e)<EOL><DEDENT>except AzureServiceBusResourceNotFound:<EOL><INDENT>raise ServiceBusResourceNotFound("<STR_LIT>")<EOL><DEDENT>return TopicClient.from_entity(<EOL>self._get_host(), topic,<EOL>shared_access_key_name=self.shared_access_key_name,<EOL>shared_access_key_value=self.shared_access_key_value,<EOL>loop=self.loop,<EOL>debug=self.debug)<EOL>

Get an async client for a topic entity.

        :param topic_name: The name of the topic.
        :type topic_name: str
        :rtype: ~azure.servicebus.aio.async_client.TopicClient
        :raises: ~azure.servicebus.common.errors.ServiceBusConnectionError if the namespace is not found.
        :raises: ~azure.servicebus.common.errors.ServiceBusResourceNotFound if the topic is not found.

        Example:
            .. literalinclude:: ../examples/async_examples/test_examples_async.py
                :start-after: [START get_async_topic_client]
                :end-before: [END get_async_topic_client]
                :language: python
                :dedent: 4
                :caption: Get a TopicClient for the specified topic.


try:<EOL><INDENT>topics = self.mgmt_client.list_topics()<EOL><DEDENT>except requests.exceptions.ConnectionError as e:<EOL><INDENT>raise ServiceBusConnectionError("<STR_LIT>".format(self.service_namespace), e)<EOL><DEDENT>topic_clients = []<EOL>for topic in topics:<EOL><INDENT>topic_clients.append(TopicClient.from_entity(<EOL>self._get_host(), topic,<EOL>shared_access_key_name=self.shared_access_key_name,<EOL>shared_access_key_value=self.shared_access_key_value,<EOL>loop=self.loop,<EOL>debug=self.debug))<EOL><DEDENT>return topic_clients<EOL>

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

        :rtype: list[~azure.servicebus.aio.async_client.TopicClient]
        :raises: ~azure.servicebus.common.errors.ServiceBusConnectionError if the namespace is not found.


try:<EOL><INDENT>subscription = self.mgmt_client.get_subscription(topic_name, subscription_name)<EOL><DEDENT>except requests.exceptions.ConnectionError as e:<EOL><INDENT>raise ServiceBusConnectionError("<STR_LIT>".format(self.service_namespace), e)<EOL><DEDENT>except AzureServiceBusResourceNotFound:<EOL><INDENT>raise ServiceBusResourceNotFound("<STR_LIT>")<EOL><DEDENT>return SubscriptionClient.from_entity(<EOL>self._get_host(), topic_name, subscription,<EOL>shared_access_key_name=self.shared_access_key_name,<EOL>shared_access_key_value=self.shared_access_key_value,<EOL>loop=self.loop,<EOL>debug=self.debug)<EOL>

Get an async client for a subscription entity.

        :param topic_name: The name of the topic.
        :type topic_name: str
        :param subscription_name: The name of the subscription.
        :type subscription_name: str
        :rtype: ~azure.servicebus.aio.async_client.SubscriptionClient
        :raises: ~azure.servicebus.common.errors.ServiceBusConnectionError if the namespace is not found.
        :raises: ~azure.servicebus.common.errors.ServiceBusResourceNotFound if the subscription is not found.

        Example:
            .. literalinclude:: ../examples/async_examples/test_examples_async.py
                :start-after: [START get_async_subscription_client]
                :end-before: [END get_async_subscription_client]
                :language: python
                :dedent: 4
                :caption: Get a TopicClient for the specified topic.


try:<EOL><INDENT>subs = self.mgmt_client.list_subscriptions(topic_name)<EOL><DEDENT>except requests.exceptions.ConnectionError as e:<EOL><INDENT>raise ServiceBusConnectionError("<STR_LIT>".format(self.service_namespace), e)<EOL><DEDENT>except AzureServiceBusResourceNotFound:<EOL><INDENT>raise ServiceBusResourceNotFound("<STR_LIT>")<EOL><DEDENT>sub_clients = []<EOL>for sub in subs:<EOL><INDENT>sub_clients.append(SubscriptionClient.from_entity(<EOL>self._get_host(), topic_name, sub,<EOL>shared_access_key_name=self.shared_access_key_name,<EOL>shared_access_key_value=self.shared_access_key_value,<EOL>loop=self.loop,<EOL>debug=self.debug))<EOL><DEDENT>return sub_clients<EOL>

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

        :param topic_name: The topic to list subscriptions for.
        :type topic_name: str
        :rtype: list[~azure.servicebus.aio.async_client.SubscriptionClient]
        :raises: ~azure.servicebus.common.errors.ServiceBusConnectionError if the namespace is not found.
        :raises: ~azure.servicebus.common.errors.ServiceBusResourceNotFound if the topic is not found.


async def send(self, messages, message_timeout=<NUM_LIT:0>, session=None, **kwargs):

async with self.get_sender(message_timeout=message_timeout, session=session, **kwargs) as sender:<EOL><INDENT>if isinstance(messages, Message):<EOL><INDENT>sender.queue_message(messages)<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>messages = list(messages)<EOL><DEDENT>except TypeError:<EOL><INDENT>raise TypeError(<EOL>"<STR_LIT>")<EOL><DEDENT>for m in messages:<EOL><INDENT>if not isinstance(m, Message):<EOL><INDENT>raise TypeError("<STR_LIT>")<EOL><DEDENT>sender.queue_message(m)<EOL><DEDENT><DEDENT>return await sender.send_pending_messages()<EOL><DEDENT>

Send one or more messages to the current entity.

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

        :param messages: One or more messages to be sent.
        :type messages: ~azure.servicebus.aio.async_message.Message or
         list[~azure.servicebus.aio.async_message.Message]
        :param message_timeout: The period in seconds during which the Message must be
         sent. If the send is not completed in this time it will return a failure result.
        :type message_timeout: int
        :param session: An optional session ID. If supplied this session ID will be
         applied to every outgoing message sent with this Sender.
         If an individual message already has a session ID, that will be
         used instead. If no session ID is supplied here, nor set on an outgoing
         message, a ValueError will be raised if the entity is sessionful.
        :type session: str or ~uuid.Guid
        :raises: ~azure.servicebus.common.errors.MessageSendFailed
        :returns: A list of the send results of all the messages. Each
         send result is a tuple with two values. The first is a boolean, indicating `True`
         if the message sent, or `False` if it failed. The second is an error if the message
         failed, otherwise it will be `None`.
        :rtype: list[tuple[bool, ~azure.servicebus.common.errors.MessageSendFailed]]

        Example:
            .. literalinclude:: ../examples/async_examples/test_examples_async.py
                :start-after: [START queue_client_send]
                :end-before: [END queue_client_send]
                :language: python
                :dedent: 4
                :caption: Send a single message.

            .. literalinclude:: ../examples/async_examples/test_examples_async.py
                :start-after: [START queue_client_send_multiple]
                :end-before: [END queue_client_send_multiple]
                :language: python
                :dedent: 4
                :caption: Send multiple messages.


Get a Sender for the Service Bus endpoint.

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

        :param message_timeout: The period in seconds during which messages sent with
         this Sender must be sent. If the send is not completed in this time it will fail.
        :type message_timeout: int
        :param session: An optional session ID. If supplied this session ID will be
         applied to every outgoing message sent with this Sender.
         If an individual message already has a session ID, that will be
         used instead. If no session ID is supplied here, nor set on an outgoing
         message, a ValueError will be raised if the entity is sessionful.
        :type session: str or ~uuid.Guid
        :returns: A Sender instance with an unopened connection.
        :rtype: ~azure.servicebus.aio.async_send_handler.Sender

        Example:
            .. literalinclude:: ../examples/async_examples/test_examples_async.py
                :start-after: [START open_close_sender_context]
                :end-before: [END open_close_sender_context]
                :language: python
                :dedent: 4
                :caption: Send multiple messages with a Sender.


async def peek(self, count=<NUM_LIT:1>, start_from=<NUM_LIT:0>, session=None, **kwargs):

message = {<EOL>'<STR_LIT>': types.AMQPLong(start_from),<EOL>'<STR_LIT>': int(count)}<EOL>if self.entity and self.requires_session:<EOL><INDENT>if not session:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>message['<STR_LIT>'] = session<EOL><DEDENT>async with BaseHandler(<EOL>self.entity_uri, self.auth_config, loop=self.loop, debug=self.debug, **kwargs) as handler:<EOL><INDENT>return await handler._mgmt_request_response(  <EOL>REQUEST_RESPONSE_PEEK_OPERATION,<EOL>message,<EOL>mgmt_handlers.peek_op)<EOL><DEDENT>

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.

        :param count: The maximum number of messages to try and peek. The default
         value is 1.
        :type count: int
        :param start_from: A message sequence number from which to start browsing messages.
        :type start_from: int
        :param session: If the entity requires sessions, a session ID must be supplied
         in order that only messages from that session will be browsed. If the entity
         does not require sessions this value will be ignored.
        :type session: str
        :rtype: list[~azure.servicebus.common.message.PeekMessage]

        Example:
            .. literalinclude:: ../examples/async_examples/test_examples_async.py
                :start-after: [START client_peek_messages]
                :end-before: [END client_peek_messages]
                :language: python
                :dedent: 4
                :caption: Peek messages in the queue.


async def receive_deferred_messages(self, sequence_numbers, mode=ReceiveSettleMode.PeekLock, **kwargs):

if (self.entity and self.requires_session) or kwargs.get('<STR_LIT>'):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if not sequence_numbers:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>try:<EOL><INDENT>receive_mode = mode.value.value<EOL><DEDENT>except AttributeError:<EOL><INDENT>receive_mode = int(mode)<EOL><DEDENT>message = {<EOL>'<STR_LIT>': types.AMQPArray([types.AMQPLong(s) for s in sequence_numbers]),<EOL>'<STR_LIT>': types.AMQPuInt(receive_mode)}<EOL>mgmt_handler = functools.partial(<EOL>mgmt_handlers.deferred_message_op, mode=receive_mode, message_type=DeferredMessage)<EOL>async with BaseHandler(<EOL>self.entity_uri, self.auth_config, loop=self.loop, debug=self.debug, **kwargs) as handler:<EOL><INDENT>return await handler._mgmt_request_response(  <EOL>REQUEST_RESPONSE_RECEIVE_BY_SEQUENCE_NUMBER,<EOL>message,<EOL>mgmt_handler)<EOL><DEDENT>

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.

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

        Example:
            .. literalinclude:: ../examples/async_examples/test_examples_async.py
                :start-after: [START client_defer_messages]
                :end-before: [END client_defer_messages]
                :language: python
                :dedent: 8
                :caption: Defer messages, then retrieve them by sequence number.


async def settle_deferred_messages(self, settlement, messages, **kwargs):

if (self.entity and self.requires_session) or kwargs.get('<STR_LIT>'):<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if settlement.lower() not in ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if not messages:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>message = {<EOL>'<STR_LIT>': settlement.lower(),<EOL>'<STR_LIT>': types.AMQPArray([m.lock_token for m in messages])}<EOL>async with BaseHandler(<EOL>self.entity_uri, self.auth_config, loop=self.loop, debug=self.debug, **kwargs) as handler:<EOL><INDENT>return await handler._mgmt_request_response(  <EOL>REQUEST_RESPONSE_UPDATE_DISPOSTION_OPERATION,<EOL>message,<EOL>mgmt_handlers.default)<EOL><DEDENT>

Settle messages that have been previously deferred.

        :param settlement: How the messages are to be settled. This must be a string
         of one of the following values: 'completed', 'suspended', 'abandoned'.
        :type settlement: str
        :param messages: A list of deferred messages to be settled.
        :type messages: list[~azure.servicebus.aio.async_message.DeferredMessage]

        Example:
            .. literalinclude:: ../examples/async_examples/test_examples_async.py
                :start-after: [START client_settle_deferred_messages]
                :end-before: [END client_settle_deferred_messages]
                :language: python
                :dedent: 4
                :caption: Settle deferred messages.


async def list_sessions(self, updated_since=None, max_results=<NUM_LIT:100>, skip=<NUM_LIT:0>, **kwargs):

if self.entity and not self.requires_session:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>message = {<EOL>'<STR_LIT>': updated_since or datetime.datetime.utcfromtimestamp(<NUM_LIT:0>),<EOL>'<STR_LIT>': types.AMQPInt(skip),<EOL>'<STR_LIT>': types.AMQPInt(max_results),<EOL>}<EOL>async with BaseHandler(<EOL>self.entity_uri, self.auth_config, loop=self.loop, debug=self.debug, **kwargs) as handler:<EOL><INDENT>return await handler._mgmt_request_response(  <EOL>REQUEST_RESPONSE_GET_MESSAGE_SESSIONS_OPERATION,<EOL>message,<EOL>mgmt_handlers.list_sessions_op)<EOL><DEDENT>

List session IDs.

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

        :param updated_since: The UTC datetime from which to return updated pending session IDs.
        :type updated_since: ~datetime.datetime
        :param max_results: The maximum number of session IDs to return. Default value is 100.
        :type max_results: int
        :param skip: The page value to jump to. Default value is 0.
        :type skip: int
        :rtype: list[str]


if self.entity and not self.requires_session and session:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if self.entity and self.requires_session and not session:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if int(prefetch) < <NUM_LIT:0> or int(prefetch) > <NUM_LIT>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>prefetch += <NUM_LIT:1><EOL>handler_id = str(uuid.uuid4())<EOL>if session:<EOL><INDENT>return SessionReceiver(<EOL>handler_id,<EOL>self.entity_uri,<EOL>self.auth_config,<EOL>session=session,<EOL>loop=self.loop,<EOL>debug=self.debug,<EOL>timeout=int(idle_timeout * <NUM_LIT:1000>),<EOL>prefetch=prefetch,<EOL>mode=mode,<EOL>**kwargs)<EOL><DEDENT>return Receiver(<EOL>handler_id,<EOL>self.entity_uri,<EOL>self.auth_config,<EOL>loop=self.loop,<EOL>debug=self.debug,<EOL>timeout=int(idle_timeout * <NUM_LIT:1000>),<EOL>prefetch=prefetch,<EOL>mode=mode,<EOL>**kwargs)<EOL>

Get a Receiver for the Service Bus endpoint.

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

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

        Example:
            .. literalinclude:: ../examples/async_examples/test_examples_async.py
                :start-after: [START open_close_receiver_context]
                :end-before: [END open_close_receiver_context]
                :language: python
                :dedent: 4
                :caption: Receive messages with a Receiver.


if int(prefetch) < <NUM_LIT:0> or int(prefetch) > <NUM_LIT>:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>prefetch += <NUM_LIT:1><EOL>handler_id = str(uuid.uuid4())<EOL>if transfer_deadletter:<EOL><INDENT>entity_uri = self.mgmt_client.format_transfer_dead_letter_queue_name(self.entity_uri)<EOL><DEDENT>else:<EOL><INDENT>entity_uri = self.mgmt_client.format_dead_letter_queue_name(self.entity_uri)<EOL><DEDENT>return Receiver(<EOL>handler_id,<EOL>entity_uri,<EOL>self.auth_config,<EOL>loop=self.loop,<EOL>debug=self.debug,<EOL>timeout=int(idle_timeout * <NUM_LIT:1000>),<EOL>prefetch=prefetch,<EOL>mode=mode,<EOL>**kwargs)<EOL>

Get a Receiver for the deadletter endpoint of the entity.

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

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

        Example:
            .. literalinclude:: ../examples/async_examples/test_examples_async.py
                :start-after: [START receiver_deadletter_messages]
                :end-before: [END receiver_deadletter_messages]
                :language: python
                :dedent: 4
                :caption: Receive dead-lettered messages.


address, policy, key, entity = parse_conn_str(conn_str)<EOL>entity = topic or entity<EOL>address = build_uri(address, entity)<EOL>address += "<STR_LIT>" + name<EOL>return cls(address, name, shared_access_key_name=policy, shared_access_key_value=key, **kwargs)<EOL>

Create a SubscriptionClient from a connection string.

        :param conn_str: The connection string.
        :type conn_str: str
        :param name: The name of the Subscription.
        :type name: str
        :param topic: The name of the Topic, if the EntityName is
         not included in the connection string.
        :type topic: str


def register(self, renewable, timeout=<NUM_LIT>):

starttime = renewable_start_time(renewable)<EOL>renew_future = asyncio.ensure_future(self._auto_lock_renew(renewable, starttime, timeout), loop=self.loop)<EOL>self._futures.append(renew_future)<EOL>

Register a renewable entity for automatic lock renewal.

        :param renewable: A locked entity that needs to be renewed.
        :type renewable: ~azure.servicebus.aio.async_message.Message or
         ~azure.servicebus.aio.async_receive_handler.SessionReceiver
        :param timeout: A time in seconds that the lock should be maintained for.
         Default value is 300 (5 minutes).
        :type timeout: int


self._shutdown.set()<EOL>await asyncio.wait(self._futures)<EOL>

Cancel remaining open lock renewal futures.


await self.open()<EOL>return self<EOL>