INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Deletes the specified OS image from your image repository.
def delete_os_image(self, image_name, delete_vhd=False): ''' Deletes the specified OS image from your image repository. image_name: The name of the image. delete_vhd: Deletes the underlying vhd blob in Azure storage. ''' _validate_not_none('image_name', image_name) path = self._get_image_path(image_name) if delete_vhd: path += '?comp=media' return self._perform_delete(path, as_async=True)
Retrieves the specified data disk from a virtual machine.
def get_data_disk(self, service_name, deployment_name, role_name, lun): ''' Retrieves the specified data disk from a virtual machine. service_name: The name of the service. deployment_name: The name of the deployment. role_name: The name of the role. lun: The Logical Unit Number (LUN) for the disk. ''' _validate_not_none('service_name', service_name) _validate_not_none('deployment_name', deployment_name) _validate_not_none('role_name', role_name) _validate_not_none('lun', lun) return self._perform_get( self._get_data_disk_path( service_name, deployment_name, role_name, lun), DataVirtualHardDisk)
Adds a data disk to a virtual machine.
def add_data_disk(self, service_name, deployment_name, role_name, lun, host_caching=None, media_link=None, disk_label=None, disk_name=None, logical_disk_size_in_gb=None, source_media_link=None): ''' Adds a data disk to a virtual machine. service_name: The name of the service. deployment_name: The name of the deployment. role_name: The name of the role. lun: Specifies the Logical Unit Number (LUN) for the disk. The LUN specifies the slot in which the data drive appears when mounted for usage by the virtual machine. Valid LUN values are 0 through 15. host_caching: Specifies the platform caching behavior of data disk blob for read/write efficiency. The default vault is ReadOnly. Possible values are: None, ReadOnly, ReadWrite media_link: Specifies the location of the blob in Windows Azure blob store where the media for the disk is located. The blob location must belong to the storage account in the subscription specified by the <subscription-id> value in the operation call. Example: http://example.blob.core.windows.net/disks/mydisk.vhd disk_label: Specifies the description of the data disk. When you attach a disk, either by directly referencing a media using the MediaLink element or specifying the target disk size, you can use the DiskLabel element to customize the name property of the target data disk. disk_name: Specifies the name of the disk. Windows Azure uses the specified disk to create the data disk for the machine and populates this field with the disk name. logical_disk_size_in_gb: Specifies the size, in GB, of an empty disk to be attached to the role. The disk can be created as part of disk attach or create VM role call by specifying the value for this property. Windows Azure creates the empty disk based on size preference and attaches the newly created disk to the Role. source_media_link: Specifies the location of a blob in account storage which is mounted as a data disk when the virtual machine is created. ''' _validate_not_none('service_name', service_name) _validate_not_none('deployment_name', deployment_name) _validate_not_none('role_name', role_name) _validate_not_none('lun', lun) return self._perform_post( self._get_data_disk_path(service_name, deployment_name, role_name), _XmlSerializer.data_virtual_hard_disk_to_xml( host_caching, disk_label, disk_name, lun, logical_disk_size_in_gb, media_link, source_media_link), as_async=True)
Updates the specified data disk attached to the specified virtual machine.
def update_data_disk(self, service_name, deployment_name, role_name, lun, host_caching=None, media_link=None, updated_lun=None, disk_label=None, disk_name=None, logical_disk_size_in_gb=None): ''' Updates the specified data disk attached to the specified virtual machine. service_name: The name of the service. deployment_name: The name of the deployment. role_name: The name of the role. lun: Specifies the Logical Unit Number (LUN) for the disk. The LUN specifies the slot in which the data drive appears when mounted for usage by the virtual machine. Valid LUN values are 0 through 15. host_caching: Specifies the platform caching behavior of data disk blob for read/write efficiency. The default vault is ReadOnly. Possible values are: None, ReadOnly, ReadWrite media_link: Specifies the location of the blob in Windows Azure blob store where the media for the disk is located. The blob location must belong to the storage account in the subscription specified by the <subscription-id> value in the operation call. Example: http://example.blob.core.windows.net/disks/mydisk.vhd updated_lun: Specifies the Logical Unit Number (LUN) for the disk. The LUN specifies the slot in which the data drive appears when mounted for usage by the virtual machine. Valid LUN values are 0 through 15. disk_label: Specifies the description of the data disk. When you attach a disk, either by directly referencing a media using the MediaLink element or specifying the target disk size, you can use the DiskLabel element to customize the name property of the target data disk. disk_name: Specifies the name of the disk. Windows Azure uses the specified disk to create the data disk for the machine and populates this field with the disk name. logical_disk_size_in_gb: Specifies the size, in GB, of an empty disk to be attached to the role. The disk can be created as part of disk attach or create VM role call by specifying the value for this property. Windows Azure creates the empty disk based on size preference and attaches the newly created disk to the Role. ''' _validate_not_none('service_name', service_name) _validate_not_none('deployment_name', deployment_name) _validate_not_none('role_name', role_name) _validate_not_none('lun', lun) return self._perform_put( self._get_data_disk_path( service_name, deployment_name, role_name, lun), _XmlSerializer.data_virtual_hard_disk_to_xml( host_caching, disk_label, disk_name, updated_lun, logical_disk_size_in_gb, media_link, None), as_async=True)
Removes the specified data disk from a virtual machine.
def delete_data_disk(self, service_name, deployment_name, role_name, lun, delete_vhd=False): ''' Removes the specified data disk from a virtual machine. service_name: The name of the service. deployment_name: The name of the deployment. role_name: The name of the role. lun: The Logical Unit Number (LUN) for the disk. delete_vhd: Deletes the underlying vhd blob in Azure storage. ''' _validate_not_none('service_name', service_name) _validate_not_none('deployment_name', deployment_name) _validate_not_none('role_name', role_name) _validate_not_none('lun', lun) path = self._get_data_disk_path(service_name, deployment_name, role_name, lun) if delete_vhd: path += '?comp=media' return self._perform_delete(path, as_async=True)
Adds a disk to the user image repository. The disk can be an OS disk or a data disk.
def add_disk(self, has_operating_system, label, media_link, name, os): ''' Adds a disk to the user image repository. The disk can be an OS disk or a data disk. has_operating_system: Deprecated. label: Specifies the description of the disk. media_link: Specifies the location of the blob in Windows Azure blob store where the media for the disk is located. The blob location must belong to the storage account in the current subscription specified by the <subscription-id> value in the operation call. Example: http://example.blob.core.windows.net/disks/mydisk.vhd name: Specifies a name for the disk. Windows Azure uses the name to identify the disk when creating virtual machines from the disk. os: The OS type of the disk. Possible values are: Linux, Windows ''' _validate_not_none('label', label) _validate_not_none('media_link', media_link) _validate_not_none('name', name) _validate_not_none('os', os) return self._perform_post(self._get_disk_path(), _XmlSerializer.disk_to_xml( label, media_link, name, os))
Updates an existing disk in your image repository.
def update_disk(self, disk_name, has_operating_system=None, label=None, media_link=None, name=None, os=None): ''' Updates an existing disk in your image repository. disk_name: The name of the disk to update. has_operating_system: Deprecated. label: Specifies the description of the disk. media_link: Deprecated. name: Deprecated. os: Deprecated. ''' _validate_not_none('disk_name', disk_name) _validate_not_none('label', label) return self._perform_put(self._get_disk_path(disk_name), _XmlSerializer.disk_to_xml( label, None, None, None))
Deletes the specified data or operating system disk from your image repository.
def delete_disk(self, disk_name, delete_vhd=False): ''' Deletes the specified data or operating system disk from your image repository. disk_name: The name of the disk to delete. delete_vhd: Deletes the underlying vhd blob in Azure storage. ''' _validate_not_none('disk_name', disk_name) path = self._get_disk_path(disk_name) if delete_vhd: path += '?comp=media' return self._perform_delete(path)
Get all smartGroups within the subscription.
def get_all( self, target_resource=None, target_resource_group=None, target_resource_type=None, monitor_service=None, monitor_condition=None, severity=None, smart_group_state=None, time_range=None, page_count=None, sort_by=None, sort_order=None, custom_headers=None, raw=False, **operation_config): """Get all smartGroups within the subscription. List all the smartGroups within the specified subscription. . :param target_resource: Filter by target resource( which is full ARM ID) Default value is select all. :type target_resource: str :param target_resource_group: Filter by target resource group name. Default value is select all. :type target_resource_group: str :param target_resource_type: Filter by target resource type. Default value is select all. :type target_resource_type: str :param monitor_service: Filter by monitor service which is the source of the alert instance. Default value is select all. Possible values include: 'Application Insights', 'ActivityLog Administrative', 'ActivityLog Security', 'ActivityLog Recommendation', 'ActivityLog Policy', 'ActivityLog Autoscale', 'Log Analytics', 'Nagios', 'Platform', 'SCOM', 'ServiceHealth', 'SmartDetector', 'VM Insights', 'Zabbix' :type monitor_service: str or ~azure.mgmt.alertsmanagement.models.MonitorService :param monitor_condition: Filter by monitor condition which is the state of the monitor(alertRule) at monitor service. Default value is to select all. Possible values include: 'Fired', 'Resolved' :type monitor_condition: str or ~azure.mgmt.alertsmanagement.models.MonitorCondition :param severity: Filter by severity. Defaut value is select all. Possible values include: 'Sev0', 'Sev1', 'Sev2', 'Sev3', 'Sev4' :type severity: str or ~azure.mgmt.alertsmanagement.models.Severity :param smart_group_state: Filter by state of the smart group. Default value is to select all. Possible values include: 'New', 'Acknowledged', 'Closed' :type smart_group_state: str or ~azure.mgmt.alertsmanagement.models.AlertState :param time_range: Filter by time range by below listed values. Default value is 1 day. Possible values include: '1h', '1d', '7d', '30d' :type time_range: str or ~azure.mgmt.alertsmanagement.models.TimeRange :param page_count: Determines number of alerts returned per page in response. Permissible value is between 1 to 250. When the "includeContent" filter is selected, maximum value allowed is 25. Default value is 25. :type page_count: int :param sort_by: Sort the query results by input field Default value is sort by 'lastModifiedDateTime'. Possible values include: 'alertsCount', 'state', 'severity', 'startDateTime', 'lastModifiedDateTime' :type sort_by: str or ~azure.mgmt.alertsmanagement.models.SmartGroupsSortByFields :param sort_order: Sort the query results order in either ascending or descending. Default value is 'desc' for time fields and 'asc' for others. Possible values include: 'asc', 'desc' :type sort_order: 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: SmartGroupsList or ClientRawResponse if raw=true :rtype: ~azure.mgmt.alertsmanagement.models.SmartGroupsList or ~msrest.pipeline.ClientRawResponse :raises: :class:`ErrorResponseException<azure.mgmt.alertsmanagement.models.ErrorResponseException>` """ # Construct URL url = self.get_all.metadata['url'] path_format_arguments = { 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} if target_resource is not None: query_parameters['targetResource'] = self._serialize.query("target_resource", target_resource, 'str') if target_resource_group is not None: query_parameters['targetResourceGroup'] = self._serialize.query("target_resource_group", target_resource_group, 'str') if target_resource_type is not None: query_parameters['targetResourceType'] = self._serialize.query("target_resource_type", target_resource_type, 'str') if monitor_service is not None: query_parameters['monitorService'] = self._serialize.query("monitor_service", monitor_service, 'str') if monitor_condition is not None: query_parameters['monitorCondition'] = self._serialize.query("monitor_condition", monitor_condition, 'str') if severity is not None: query_parameters['severity'] = self._serialize.query("severity", severity, 'str') if smart_group_state is not None: query_parameters['smartGroupState'] = self._serialize.query("smart_group_state", smart_group_state, 'str') if time_range is not None: query_parameters['timeRange'] = self._serialize.query("time_range", time_range, 'str') if page_count is not None: query_parameters['pageCount'] = self._serialize.query("page_count", page_count, 'int') if sort_by is not None: query_parameters['sortBy'] = self._serialize.query("sort_by", sort_by, 'str') if sort_order is not None: query_parameters['sortOrder'] = self._serialize.query("sort_order", sort_order, 'str') query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') # Construct headers header_parameters = {} header_parameters['Accept'] = 'application/json' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct and send request request = self._client.get(url, query_parameters, header_parameters) response = self._client.send(request, stream=False, **operation_config) if response.status_code not in [200]: raise models.ErrorResponseException(self._deserialize, response) deserialized = None if response.status_code == 200: deserialized = self._deserialize('SmartGroupsList', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized
Summarizes policy states for the resources under the management group.
def summarize_for_management_group( self, management_group_name, query_options=None, custom_headers=None, raw=False, **operation_config): """Summarizes policy states for the resources under the management group. :param management_group_name: Management group name. :type management_group_name: str :param query_options: Additional parameters for the operation :type query_options: ~azure.mgmt.policyinsights.models.QueryOptions :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: SummarizeResults or ClientRawResponse if raw=true :rtype: ~azure.mgmt.policyinsights.models.SummarizeResults or ~msrest.pipeline.ClientRawResponse :raises: :class:`QueryFailureException<azure.mgmt.policyinsights.models.QueryFailureException>` """ top = None if query_options is not None: top = query_options.top from_parameter = None if query_options is not None: from_parameter = query_options.from_property to = None if query_options is not None: to = query_options.to filter = None if query_options is not None: filter = query_options.filter # Construct URL url = self.summarize_for_management_group.metadata['url'] path_format_arguments = { 'policyStatesSummaryResource': self._serialize.url("self.policy_states_summary_resource", self.policy_states_summary_resource, 'str'), 'managementGroupsNamespace': self._serialize.url("self.management_groups_namespace", self.management_groups_namespace, 'str'), 'managementGroupName': self._serialize.url("management_group_name", management_group_name, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') if top is not None: query_parameters['$top'] = self._serialize.query("top", top, 'int', minimum=0) if from_parameter is not None: query_parameters['$from'] = self._serialize.query("from_parameter", from_parameter, 'iso-8601') if to is not None: query_parameters['$to'] = self._serialize.query("to", to, 'iso-8601') if filter is not None: query_parameters['$filter'] = self._serialize.query("filter", filter, 'str') # Construct headers header_parameters = {} header_parameters['Accept'] = 'application/json' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct and send request request = self._client.post(url, query_parameters, header_parameters) response = self._client.send(request, stream=False, **operation_config) if response.status_code not in [200]: raise models.QueryFailureException(self._deserialize, response) deserialized = None if response.status_code == 200: deserialized = self._deserialize('SummarizeResults', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized
This is a temporary patch pending a fix in uAMQP.
def _build_receiver(self): """This is a temporary patch pending a fix in uAMQP.""" # pylint: disable=protected-access self._handler.message_handler = self._handler.receiver_type( self._handler._session, self._handler._remote_address, self._handler._name, on_message_received=self._handler._message_received, name='receiver-link-{}'.format(uuid.uuid4()), debug=self._handler._debug_trace, prefetch=self._handler._prefetch, max_message_size=self._handler._max_message_size, properties=self._handler._link_properties, error_policy=self._handler._error_policy, encoding=self._handler._encoding) if self.mode != ReceiveSettleMode.PeekLock: self._handler.message_handler.send_settle_mode = constants.SenderSettleMode.Settled self._handler.message_handler.receive_settle_mode = constants.ReceiverSettleMode.ReceiveAndDelete self._handler.message_handler._settle_mode = constants.ReceiverSettleMode.ReceiveAndDelete self._handler.message_handler.open()
Open receiver connection and authenticate session.
def open(self): """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 self.running: return self.running = True try: self._handler.open(connection=self.connection) self.message_iter = self._handler.receive_messages_iter() while not self._handler.auth_complete(): time.sleep(0.05) self._build_receiver() while not self._handler.client_ready(): time.sleep(0.05) except Exception as e: # pylint: disable=broad-except try: self._handle_exception(e) except: self.running = False raise
Receive a batch of messages at once.
def fetch_next(self, max_batch_size=None, timeout=None): """Receive a batch of messages at once. This approach it optimal if you wish to process multiple messages simultaneously. Note that the number of messages retrieved in a single batch will be dependent on whether `prefetch` was set for the receiver. This call will prioritize returning quickly over meeting a specified batch size, and so will return as soon as at least one message is received and there is a gap in incoming messages regardless of the specified batch size. :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() wrapped_batch = [] max_batch_size = max_batch_size or self._handler._prefetch # pylint: disable=protected-access try: timeout_ms = 1000 * timeout if timeout else 0 batch = self._handler.receive_message_batch( max_batch_size=max_batch_size, timeout=timeout_ms) for received in batch: message = self._build_message(received) wrapped_batch.append(message) except Exception as e: # pylint: disable=broad-except self._handle_exception(e) return wrapped_batch
Renew the session lock.
def renew_lock(self): """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 """ self._can_run() expiry = self._mgmt_request_response( REQUEST_RESPONSE_RENEW_SESSION_LOCK_OPERATION, {'session-id': self.session_id}, mgmt_handlers.default) self.locked_until = datetime.datetime.fromtimestamp(expiry[b'expiration']/1000.0)
Browse messages currently pending in the queue.
def peek(self, count=1, start_from=None): """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 start_from: start_from = self.last_received or 1 if int(count) < 1: raise ValueError("count must be 1 or greater.") if int(start_from) < 1: raise ValueError("start_from must be 1 or greater.") self._can_run() message = { 'from-sequence-number': types.AMQPLong(start_from), 'message-count': count, 'session-id': self.session_id} return self._mgmt_request_response( REQUEST_RESPONSE_PEEK_OPERATION, message, mgmt_handlers.peek_op)
List session IDs.
def list_sessions(self, updated_since=None, max_results=100, skip=0): """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 """ if int(max_results) < 1: raise ValueError("max_results must be 1 or greater.") self._can_run() message = { 'last-updated-time': updated_since or datetime.datetime.utcfromtimestamp(0), 'skip': skip, 'top': max_results, } return self._mgmt_request_response( REQUEST_RESPONSE_GET_MESSAGE_SESSIONS_OPERATION, message, mgmt_handlers.list_sessions_op)
Create or update a VM scale set.
def create_or_update( self, resource_group_name, vm_scale_set_name, parameters, custom_headers=None, raw=False, polling=True, **operation_config): """Create or update a VM scale set. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param vm_scale_set_name: The name of the VM scale set to create or update. :type vm_scale_set_name: str :param parameters: The scale set object. :type parameters: ~azure.mgmt.compute.v2019_03_01.models.VirtualMachineScaleSet :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 VirtualMachineScaleSet or ClientRawResponse<VirtualMachineScaleSet> if raw==True :rtype: ~msrestazure.azure_operation.AzureOperationPoller[~azure.mgmt.compute.v2019_03_01.models.VirtualMachineScaleSet] or ~msrestazure.azure_operation.AzureOperationPoller[~msrest.pipeline.ClientRawResponse[~azure.mgmt.compute.v2019_03_01.models.VirtualMachineScaleSet]] :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>` """ raw_result = self._create_or_update_initial( resource_group_name=resource_group_name, vm_scale_set_name=vm_scale_set_name, parameters=parameters, custom_headers=custom_headers, raw=True, **operation_config ) def get_long_running_output(response): deserialized = self._deserialize('VirtualMachineScaleSet', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized lro_delay = operation_config.get( 'long_running_operation_timeout', self.config.long_running_operation_timeout) if polling is True: polling_method = ARMPolling(lro_delay, **operation_config) elif polling is False: polling_method = NoPolling() else: polling_method = polling return LROPoller(self._client, raw_result, get_long_running_output, polling_method)
Converts SinglePlacementGroup property to false for a existing virtual machine scale set.
def convert_to_single_placement_group( self, resource_group_name, vm_scale_set_name, active_placement_group_id=None, custom_headers=None, raw=False, **operation_config): """Converts SinglePlacementGroup property to false for a existing virtual machine scale set. :param resource_group_name: The name of the resource group. :type resource_group_name: str :param vm_scale_set_name: The name of the virtual machine scale set to create or update. :type vm_scale_set_name: str :param active_placement_group_id: Id of the placement group in which you want future virtual machine instances to be placed. To query placement group Id, please use Virtual Machine Scale Set VMs - Get API. If not provided, the platform will choose one with maximum number of virtual machine instances. :type active_placement_group_id: 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: None or ClientRawResponse if raw=true :rtype: None or ~msrest.pipeline.ClientRawResponse :raises: :class:`CloudError<msrestazure.azure_exceptions.CloudError>` """ parameters = models.VMScaleSetConvertToSinglePlacementGroupInput(active_placement_group_id=active_placement_group_id) # Construct URL url = self.convert_to_single_placement_group.metadata['url'] path_format_arguments = { 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'vmScaleSetName': self._serialize.url("vm_scale_set_name", vm_scale_set_name, 'str'), 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # Construct headers header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct body body_content = self._serialize.body(parameters, 'VMScaleSetConvertToSinglePlacementGroupInput') # Construct and send request request = self._client.post(url, query_parameters, header_parameters, body_content) response = self._client.send(request, stream=False, **operation_config) if response.status_code not in [200]: exp = CloudError(response) exp.request_id = response.headers.get('x-ms-request-id') raise exp if raw: client_raw_response = ClientRawResponse(None, response) return client_raw_response
Find all Autorest generated code in that module prefix. This actually looks for a models package only ( not file ). We could be smarter if necessary.
def find_autorest_generated_folder(module_prefix="azure"): """Find all Autorest generated code in that module prefix. This actually looks for a "models" package only (not file). We could be smarter if necessary. """ _LOGGER.info(f"Looking for Autorest generated package in {module_prefix}") # Manually skip some namespaces for now if module_prefix in ["azure.cli", "azure.storage", "azure.servicemanagement", "azure.servicebus"]: _LOGGER.info(f"Skip {module_prefix}") return [] result = [] try: _LOGGER.debug(f"Try {module_prefix}") model_module = importlib.import_module(".models", module_prefix) # If not exception, we MIGHT have found it, but cannot be a file. # Keep continue to try to break it, file module have no __path__ model_module.__path__ _LOGGER.info(f"Found {module_prefix}") result.append(module_prefix) except (ModuleNotFoundError, AttributeError): # No model, might dig deeper prefix_module = importlib.import_module(module_prefix) for _, sub_package, ispkg in pkgutil.iter_modules(prefix_module.__path__, module_prefix+"."): if ispkg: result += find_autorest_generated_folder(sub_package) return result
Assuming package is azure - mgmt - compute and module name is azure. mgmt. compute. v2018 - 08 - 01 will return v2018 - 08 - 01
def get_sub_module_part(package_name, module_name): """Assuming package is azure-mgmt-compute and module name is azure.mgmt.compute.v2018-08-01 will return v2018-08-01 """ sub_module_from_package = package_name.replace("-", ".") if not module_name.startswith(sub_module_from_package): _LOGGER.warning(f"Submodule {module_name} does not start with package name {package_name}") return return module_name[len(sub_module_from_package)+1:]
Module depends on the API version:
def models(cls, api_version=DEFAULT_API_VERSION): """Module depends on the API version: * 2016-02-01: :mod:`v2016_02_01.models<azure.mgmt.resource.resources.v2016_02_01.models>` * 2016-09-01: :mod:`v2016_09_01.models<azure.mgmt.resource.resources.v2016_09_01.models>` * 2017-05-10: :mod:`v2017_05_10.models<azure.mgmt.resource.resources.v2017_05_10.models>` * 2018-02-01: :mod:`v2018_02_01.models<azure.mgmt.resource.resources.v2018_02_01.models>` * 2018-05-01: :mod:`v2018_05_01.models<azure.mgmt.resource.resources.v2018_05_01.models>` """ if api_version == '2016-02-01': from .v2016_02_01 import models return models elif api_version == '2016-09-01': from .v2016_09_01 import models return models elif api_version == '2017-05-10': from .v2017_05_10 import models return models elif api_version == '2018-02-01': from .v2018_02_01 import models return models elif api_version == '2018-05-01': from .v2018_05_01 import models return models raise NotImplementedError("APIVersion {} is not available".format(api_version))
Instance depends on the API version:
def resource_groups(self): """Instance depends on the API version: * 2016-02-01: :class:`ResourceGroupsOperations<azure.mgmt.resource.resources.v2016_02_01.operations.ResourceGroupsOperations>` * 2016-09-01: :class:`ResourceGroupsOperations<azure.mgmt.resource.resources.v2016_09_01.operations.ResourceGroupsOperations>` * 2017-05-10: :class:`ResourceGroupsOperations<azure.mgmt.resource.resources.v2017_05_10.operations.ResourceGroupsOperations>` * 2018-02-01: :class:`ResourceGroupsOperations<azure.mgmt.resource.resources.v2018_02_01.operations.ResourceGroupsOperations>` * 2018-05-01: :class:`ResourceGroupsOperations<azure.mgmt.resource.resources.v2018_05_01.operations.ResourceGroupsOperations>` """ api_version = self._get_api_version('resource_groups') if api_version == '2016-02-01': from .v2016_02_01.operations import ResourceGroupsOperations as OperationClass elif api_version == '2016-09-01': from .v2016_09_01.operations import ResourceGroupsOperations as OperationClass elif api_version == '2017-05-10': from .v2017_05_10.operations import ResourceGroupsOperations as OperationClass elif api_version == '2018-02-01': from .v2018_02_01.operations import ResourceGroupsOperations as OperationClass elif api_version == '2018-05-01': from .v2018_05_01.operations import ResourceGroupsOperations as OperationClass else: raise NotImplementedError("APIVersion {} is not available".format(api_version)) return OperationClass(self._client, self.config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)))
Module depends on the API version:
def models(cls, api_version=DEFAULT_API_VERSION): """Module depends on the API version: * 2015-10-01-preview: :mod:`v2015_10_01_preview.models<azure.mgmt.resource.policy.v2015_10_01_preview.models>` * 2016-04-01: :mod:`v2016_04_01.models<azure.mgmt.resource.policy.v2016_04_01.models>` * 2016-12-01: :mod:`v2016_12_01.models<azure.mgmt.resource.policy.v2016_12_01.models>` * 2017-06-01-preview: :mod:`v2017_06_01_preview.models<azure.mgmt.resource.policy.v2017_06_01_preview.models>` * 2018-03-01: :mod:`v2018_03_01.models<azure.mgmt.resource.policy.v2018_03_01.models>` * 2018-05-01: :mod:`v2018_05_01.models<azure.mgmt.resource.policy.v2018_05_01.models>` """ if api_version == '2015-10-01-preview': from .v2015_10_01_preview import models return models elif api_version == '2016-04-01': from .v2016_04_01 import models return models elif api_version == '2016-12-01': from .v2016_12_01 import models return models elif api_version == '2017-06-01-preview': from .v2017_06_01_preview import models return models elif api_version == '2018-03-01': from .v2018_03_01 import models return models elif api_version == '2018-05-01': from .v2018_05_01 import models return models raise NotImplementedError("APIVersion {} is not available".format(api_version))
Instance depends on the API version:
def policy_assignments(self): """Instance depends on the API version: * 2015-10-01-preview: :class:`PolicyAssignmentsOperations<azure.mgmt.resource.policy.v2015_10_01_preview.operations.PolicyAssignmentsOperations>` * 2016-04-01: :class:`PolicyAssignmentsOperations<azure.mgmt.resource.policy.v2016_04_01.operations.PolicyAssignmentsOperations>` * 2016-12-01: :class:`PolicyAssignmentsOperations<azure.mgmt.resource.policy.v2016_12_01.operations.PolicyAssignmentsOperations>` * 2017-06-01-preview: :class:`PolicyAssignmentsOperations<azure.mgmt.resource.policy.v2017_06_01_preview.operations.PolicyAssignmentsOperations>` * 2018-03-01: :class:`PolicyAssignmentsOperations<azure.mgmt.resource.policy.v2018_03_01.operations.PolicyAssignmentsOperations>` * 2018-05-01: :class:`PolicyAssignmentsOperations<azure.mgmt.resource.policy.v2018_05_01.operations.PolicyAssignmentsOperations>` """ api_version = self._get_api_version('policy_assignments') if api_version == '2015-10-01-preview': from .v2015_10_01_preview.operations import PolicyAssignmentsOperations as OperationClass elif api_version == '2016-04-01': from .v2016_04_01.operations import PolicyAssignmentsOperations as OperationClass elif api_version == '2016-12-01': from .v2016_12_01.operations import PolicyAssignmentsOperations as OperationClass elif api_version == '2017-06-01-preview': from .v2017_06_01_preview.operations import PolicyAssignmentsOperations as OperationClass elif api_version == '2018-03-01': from .v2018_03_01.operations import PolicyAssignmentsOperations as OperationClass elif api_version == '2018-05-01': from .v2018_05_01.operations import PolicyAssignmentsOperations as OperationClass else: raise NotImplementedError("APIVersion {} is not available".format(api_version)) return OperationClass(self._client, self.config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)))
Instance depends on the API version:
def policy_set_definitions(self): """Instance depends on the API version: * 2017-06-01-preview: :class:`PolicySetDefinitionsOperations<azure.mgmt.resource.policy.v2017_06_01_preview.operations.PolicySetDefinitionsOperations>` * 2018-03-01: :class:`PolicySetDefinitionsOperations<azure.mgmt.resource.policy.v2018_03_01.operations.PolicySetDefinitionsOperations>` * 2018-05-01: :class:`PolicySetDefinitionsOperations<azure.mgmt.resource.policy.v2018_05_01.operations.PolicySetDefinitionsOperations>` """ api_version = self._get_api_version('policy_set_definitions') if api_version == '2017-06-01-preview': from .v2017_06_01_preview.operations import PolicySetDefinitionsOperations as OperationClass elif api_version == '2018-03-01': from .v2018_03_01.operations import PolicySetDefinitionsOperations as OperationClass elif api_version == '2018-05-01': from .v2018_05_01.operations import PolicySetDefinitionsOperations as OperationClass else: raise NotImplementedError("APIVersion {} is not available".format(api_version)) return OperationClass(self._client, self.config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)))
Detect profanity and match against custom and shared blacklists.
def screen_text( self, text_content_type, text_content, language=None, autocorrect=False, pii=False, list_id=None, classify=False, custom_headers=None, raw=False, callback=None, **operation_config): """Detect profanity and match against custom and shared blacklists. Detects profanity in more than 100 languages and match against custom and shared blacklists. :param text_content_type: The content type. Possible values include: 'text/plain', 'text/html', 'text/xml', 'text/markdown' :type text_content_type: str :param text_content: Content to screen. :type text_content: Generator :param language: Language of the text. :type language: str :param autocorrect: Autocorrect text. :type autocorrect: bool :param pii: Detect personal identifiable information. :type pii: bool :param list_id: The list Id. :type list_id: str :param classify: Classify input. :type classify: bool :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :param callback: When specified, will be called with each chunk of data that is streamed. The callback should take two arguments, the bytes of the current chunk of data and the response object. If the data is uploading, response will be None. :type callback: Callable[Bytes, response=None] :param operation_config: :ref:`Operation configuration overrides<msrest:optionsforoperations>`. :return: Screen or ClientRawResponse if raw=true :rtype: ~azure.cognitiveservices.vision.contentmoderator.models.Screen or ~msrest.pipeline.ClientRawResponse :raises: :class:`APIErrorException<azure.cognitiveservices.vision.contentmoderator.models.APIErrorException>` """ # Construct URL url = self.screen_text.metadata['url'] path_format_arguments = { 'Endpoint': self._serialize.url("self.config.endpoint", self.config.endpoint, 'str', skip_quote=True) } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} if language is not None: query_parameters['language'] = self._serialize.query("language", language, 'str') if autocorrect is not None: query_parameters['autocorrect'] = self._serialize.query("autocorrect", autocorrect, 'bool') if pii is not None: query_parameters['PII'] = self._serialize.query("pii", pii, 'bool') if list_id is not None: query_parameters['listId'] = self._serialize.query("list_id", list_id, 'str') if classify is not None: query_parameters['classify'] = self._serialize.query("classify", classify, 'bool') # Construct headers header_parameters = {} header_parameters['Accept'] = 'application/json' header_parameters['Content-Type'] = 'text/plain' if custom_headers: header_parameters.update(custom_headers) header_parameters['Content-Type'] = self._serialize.header("text_content_type", text_content_type, 'str') # Construct body body_content = self._client.stream_upload(text_content, callback) # Construct and send request request = self._client.post(url, query_parameters, header_parameters, body_content) response = self._client.send(request, stream=False, **operation_config) if response.status_code not in [200]: raise models.APIErrorException(self._deserialize, response) deserialized = None if response.status_code == 200: deserialized = self._deserialize('Screen', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized
Creates a new key stores it then returns key parameters and attributes to the client.
def create_key( self, vault_base_url, key_name, kty, key_size=None, key_ops=None, key_attributes=None, tags=None, curve=None, custom_headers=None, raw=False, **operation_config): """Creates a new key, stores it, then returns key parameters and attributes to the client. The create key operation can be used to create any key type in Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the key. It requires the keys/create permission. :param vault_base_url: The vault name, for example https://myvault.vault.azure.net. :type vault_base_url: str :param key_name: The name for the new key. The system will generate the version name for the new key. :type key_name: str :param kty: The type of key to create. For valid values, see JsonWebKeyType. Possible values include: 'EC', 'EC-HSM', 'RSA', 'RSA-HSM', 'oct' :type kty: str or ~azure.keyvault.v2016_10_01.models.JsonWebKeyType :param key_size: The key size in bits. For example: 2048, 3072, or 4096 for RSA. :type key_size: int :param key_ops: :type key_ops: list[str or ~azure.keyvault.v2016_10_01.models.JsonWebKeyOperation] :param key_attributes: :type key_attributes: ~azure.keyvault.v2016_10_01.models.KeyAttributes :param tags: Application specific metadata in the form of key-value pairs. :type tags: dict[str, str] :param curve: Elliptic curve name. For valid values, see JsonWebKeyCurveName. Possible values include: 'P-256', 'P-384', 'P-521', 'SECP256K1' :type curve: str or ~azure.keyvault.v2016_10_01.models.JsonWebKeyCurveName :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: KeyBundle or ClientRawResponse if raw=true :rtype: ~azure.keyvault.v2016_10_01.models.KeyBundle or ~msrest.pipeline.ClientRawResponse :raises: :class:`KeyVaultErrorException<azure.keyvault.v2016_10_01.models.KeyVaultErrorException>` """ parameters = models.KeyCreateParameters(kty=kty, key_size=key_size, key_ops=key_ops, key_attributes=key_attributes, tags=tags, curve=curve) # Construct URL url = self.create_key.metadata['url'] path_format_arguments = { 'vaultBaseUrl': self._serialize.url("vault_base_url", vault_base_url, 'str', skip_quote=True), 'key-name': self._serialize.url("key_name", key_name, 'str', pattern=r'^[0-9a-zA-Z-]+$') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') # Construct headers header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct body body_content = self._serialize.body(parameters, 'KeyCreateParameters') # Construct and send request request = self._client.post(url, query_parameters) response = self._client.send( request, header_parameters, body_content, stream=False, **operation_config) if response.status_code not in [200]: raise models.KeyVaultErrorException(self._deserialize, response) deserialized = None if response.status_code == 200: deserialized = self._deserialize('KeyBundle', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized
Imports an externally created key stores it and returns key parameters and attributes to the client.
def import_key( self, vault_base_url, key_name, key, hsm=None, key_attributes=None, tags=None, custom_headers=None, raw=False, **operation_config): """Imports an externally created key, stores it, and returns key parameters and attributes to the client. The import key operation may be used to import any key type into an Azure Key Vault. If the named key already exists, Azure Key Vault creates a new version of the key. This operation requires the keys/import permission. :param vault_base_url: The vault name, for example https://myvault.vault.azure.net. :type vault_base_url: str :param key_name: Name for the imported key. :type key_name: str :param key: The Json web key :type key: ~azure.keyvault.v2016_10_01.models.JsonWebKey :param hsm: Whether to import as a hardware key (HSM) or software key. :type hsm: bool :param key_attributes: The key management attributes. :type key_attributes: ~azure.keyvault.v2016_10_01.models.KeyAttributes :param tags: Application specific metadata in the form of key-value pairs. :type tags: dict[str, 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: KeyBundle or ClientRawResponse if raw=true :rtype: ~azure.keyvault.v2016_10_01.models.KeyBundle or ~msrest.pipeline.ClientRawResponse :raises: :class:`KeyVaultErrorException<azure.keyvault.v2016_10_01.models.KeyVaultErrorException>` """ parameters = models.KeyImportParameters(hsm=hsm, key=key, key_attributes=key_attributes, tags=tags) # Construct URL url = self.import_key.metadata['url'] path_format_arguments = { 'vaultBaseUrl': self._serialize.url("vault_base_url", vault_base_url, 'str', skip_quote=True), 'key-name': self._serialize.url("key_name", key_name, 'str', pattern=r'^[0-9a-zA-Z-]+$') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') # Construct headers header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct body body_content = self._serialize.body(parameters, 'KeyImportParameters') # Construct and send request request = self._client.put(url, query_parameters) response = self._client.send( request, header_parameters, body_content, stream=False, **operation_config) if response.status_code not in [200]: raise models.KeyVaultErrorException(self._deserialize, response) deserialized = None if response.status_code == 200: deserialized = self._deserialize('KeyBundle', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized
The update key operation changes specified attributes of a stored key and can be applied to any key type and key version stored in Azure Key Vault.
def update_key( self, vault_base_url, key_name, key_version, key_ops=None, key_attributes=None, tags=None, custom_headers=None, raw=False, **operation_config): """The update key operation changes specified attributes of a stored key and can be applied to any key type and key version stored in Azure Key Vault. In order to perform this operation, the key must already exist in the Key Vault. Note: The cryptographic material of a key itself cannot be changed. This operation requires the keys/update permission. :param vault_base_url: The vault name, for example https://myvault.vault.azure.net. :type vault_base_url: str :param key_name: The name of key to update. :type key_name: str :param key_version: The version of the key to update. :type key_version: str :param key_ops: Json web key operations. For more information on possible key operations, see JsonWebKeyOperation. :type key_ops: list[str or ~azure.keyvault.v2016_10_01.models.JsonWebKeyOperation] :param key_attributes: :type key_attributes: ~azure.keyvault.v2016_10_01.models.KeyAttributes :param tags: Application specific metadata in the form of key-value pairs. :type tags: dict[str, 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: KeyBundle or ClientRawResponse if raw=true :rtype: ~azure.keyvault.v2016_10_01.models.KeyBundle or ~msrest.pipeline.ClientRawResponse :raises: :class:`KeyVaultErrorException<azure.keyvault.v2016_10_01.models.KeyVaultErrorException>` """ parameters = models.KeyUpdateParameters(key_ops=key_ops, key_attributes=key_attributes, tags=tags) # Construct URL url = self.update_key.metadata['url'] path_format_arguments = { 'vaultBaseUrl': self._serialize.url("vault_base_url", vault_base_url, 'str', skip_quote=True), 'key-name': self._serialize.url("key_name", key_name, 'str'), 'key-version': self._serialize.url("key_version", key_version, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') # Construct headers header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct body body_content = self._serialize.body(parameters, 'KeyUpdateParameters') # Construct and send request request = self._client.patch(url, query_parameters) response = self._client.send( request, header_parameters, body_content, stream=False, **operation_config) if response.status_code not in [200]: raise models.KeyVaultErrorException(self._deserialize, response) deserialized = None if response.status_code == 200: deserialized = self._deserialize('KeyBundle', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized
Sets a secret in a specified key vault.
def set_secret( self, vault_base_url, secret_name, value, tags=None, content_type=None, secret_attributes=None, custom_headers=None, raw=False, **operation_config): """Sets a secret in a specified key vault. The SET operation adds a secret to the Azure Key Vault. If the named secret already exists, Azure Key Vault creates a new version of that secret. This operation requires the secrets/set permission. :param vault_base_url: The vault name, for example https://myvault.vault.azure.net. :type vault_base_url: str :param secret_name: The name of the secret. :type secret_name: str :param value: The value of the secret. :type value: str :param tags: Application specific metadata in the form of key-value pairs. :type tags: dict[str, str] :param content_type: Type of the secret value such as a password. :type content_type: str :param secret_attributes: The secret management attributes. :type secret_attributes: ~azure.keyvault.v2016_10_01.models.SecretAttributes :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: SecretBundle or ClientRawResponse if raw=true :rtype: ~azure.keyvault.v2016_10_01.models.SecretBundle or ~msrest.pipeline.ClientRawResponse :raises: :class:`KeyVaultErrorException<azure.keyvault.v2016_10_01.models.KeyVaultErrorException>` """ parameters = models.SecretSetParameters(value=value, tags=tags, content_type=content_type, secret_attributes=secret_attributes) # Construct URL url = self.set_secret.metadata['url'] path_format_arguments = { 'vaultBaseUrl': self._serialize.url("vault_base_url", vault_base_url, 'str', skip_quote=True), 'secret-name': self._serialize.url("secret_name", secret_name, 'str', pattern=r'^[0-9a-zA-Z-]+$') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') # Construct headers header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct body body_content = self._serialize.body(parameters, 'SecretSetParameters') # Construct and send request request = self._client.put(url, query_parameters) response = self._client.send( request, header_parameters, body_content, stream=False, **operation_config) if response.status_code not in [200]: raise models.KeyVaultErrorException(self._deserialize, response) deserialized = None if response.status_code == 200: deserialized = self._deserialize('SecretBundle', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized
Sets the specified certificate issuer.
def set_certificate_issuer( self, vault_base_url, issuer_name, provider, credentials=None, organization_details=None, attributes=None, custom_headers=None, raw=False, **operation_config): """Sets the specified certificate issuer. The SetCertificateIssuer operation adds or updates the specified certificate issuer. This operation requires the certificates/setissuers permission. :param vault_base_url: The vault name, for example https://myvault.vault.azure.net. :type vault_base_url: str :param issuer_name: The name of the issuer. :type issuer_name: str :param provider: The issuer provider. :type provider: str :param credentials: The credentials to be used for the issuer. :type credentials: ~azure.keyvault.v2016_10_01.models.IssuerCredentials :param organization_details: Details of the organization as provided to the issuer. :type organization_details: ~azure.keyvault.v2016_10_01.models.OrganizationDetails :param attributes: Attributes of the issuer object. :type attributes: ~azure.keyvault.v2016_10_01.models.IssuerAttributes :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: IssuerBundle or ClientRawResponse if raw=true :rtype: ~azure.keyvault.v2016_10_01.models.IssuerBundle or ~msrest.pipeline.ClientRawResponse :raises: :class:`KeyVaultErrorException<azure.keyvault.v2016_10_01.models.KeyVaultErrorException>` """ parameter = models.CertificateIssuerSetParameters(provider=provider, credentials=credentials, organization_details=organization_details, attributes=attributes) # Construct URL url = self.set_certificate_issuer.metadata['url'] path_format_arguments = { 'vaultBaseUrl': self._serialize.url("vault_base_url", vault_base_url, 'str', skip_quote=True), 'issuer-name': self._serialize.url("issuer_name", issuer_name, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') # Construct headers header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct body body_content = self._serialize.body(parameter, 'CertificateIssuerSetParameters') # Construct and send request request = self._client.put(url, query_parameters) response = self._client.send( request, header_parameters, body_content, stream=False, **operation_config) if response.status_code not in [200]: raise models.KeyVaultErrorException(self._deserialize, response) deserialized = None if response.status_code == 200: deserialized = self._deserialize('IssuerBundle', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized
Creates or updates a new storage account. This operation requires the storage/ set permission.
def set_storage_account( self, vault_base_url, storage_account_name, resource_id, active_key_name, auto_regenerate_key, regeneration_period=None, storage_account_attributes=None, tags=None, custom_headers=None, raw=False, **operation_config): """Creates or updates a new storage account. This operation requires the storage/set permission. :param vault_base_url: The vault name, for example https://myvault.vault.azure.net. :type vault_base_url: str :param storage_account_name: The name of the storage account. :type storage_account_name: str :param resource_id: Storage account resource id. :type resource_id: str :param active_key_name: Current active storage account key name. :type active_key_name: str :param auto_regenerate_key: whether keyvault should manage the storage account for the user. :type auto_regenerate_key: bool :param regeneration_period: The key regeneration time duration specified in ISO-8601 format. :type regeneration_period: str :param storage_account_attributes: The attributes of the storage account. :type storage_account_attributes: ~azure.keyvault.v2016_10_01.models.StorageAccountAttributes :param tags: Application specific metadata in the form of key-value pairs. :type tags: dict[str, 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: StorageBundle or ClientRawResponse if raw=true :rtype: ~azure.keyvault.v2016_10_01.models.StorageBundle or ~msrest.pipeline.ClientRawResponse :raises: :class:`KeyVaultErrorException<azure.keyvault.v2016_10_01.models.KeyVaultErrorException>` """ parameters = models.StorageAccountCreateParameters(resource_id=resource_id, active_key_name=active_key_name, auto_regenerate_key=auto_regenerate_key, regeneration_period=regeneration_period, storage_account_attributes=storage_account_attributes, tags=tags) # Construct URL url = self.set_storage_account.metadata['url'] path_format_arguments = { 'vaultBaseUrl': self._serialize.url("vault_base_url", vault_base_url, 'str', skip_quote=True), 'storage-account-name': self._serialize.url("storage_account_name", storage_account_name, 'str', pattern=r'^[0-9a-zA-Z]+$') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') # Construct headers header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct body body_content = self._serialize.body(parameters, 'StorageAccountCreateParameters') # Construct and send request request = self._client.put(url, query_parameters) response = self._client.send( request, header_parameters, body_content, stream=False, **operation_config) if response.status_code not in [200]: raise models.KeyVaultErrorException(self._deserialize, response) deserialized = None if response.status_code == 200: deserialized = self._deserialize('StorageBundle', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized
Module depends on the API version:
def models(cls, api_version=DEFAULT_API_VERSION): """Module depends on the API version: * 2015-06-15: :mod:`v2015_06_15.models<azure.mgmt.storage.v2015_06_15.models>` * 2016-01-01: :mod:`v2016_01_01.models<azure.mgmt.storage.v2016_01_01.models>` * 2016-12-01: :mod:`v2016_12_01.models<azure.mgmt.storage.v2016_12_01.models>` * 2017-06-01: :mod:`v2017_06_01.models<azure.mgmt.storage.v2017_06_01.models>` * 2017-10-01: :mod:`v2017_10_01.models<azure.mgmt.storage.v2017_10_01.models>` * 2018-02-01: :mod:`v2018_02_01.models<azure.mgmt.storage.v2018_02_01.models>` * 2018-03-01-preview: :mod:`v2018_03_01_preview.models<azure.mgmt.storage.v2018_03_01_preview.models>` * 2018-07-01: :mod:`v2018_07_01.models<azure.mgmt.storage.v2018_07_01.models>` """ if api_version == '2015-06-15': from .v2015_06_15 import models return models elif api_version == '2016-01-01': from .v2016_01_01 import models return models elif api_version == '2016-12-01': from .v2016_12_01 import models return models elif api_version == '2017-06-01': from .v2017_06_01 import models return models elif api_version == '2017-10-01': from .v2017_10_01 import models return models elif api_version == '2018-02-01': from .v2018_02_01 import models return models elif api_version == '2018-03-01-preview': from .v2018_03_01_preview import models return models elif api_version == '2018-07-01': from .v2018_07_01 import models return models raise NotImplementedError("APIVersion {} is not available".format(api_version))
Instance depends on the API version:
def blob_containers(self): """Instance depends on the API version: * 2018-02-01: :class:`BlobContainersOperations<azure.mgmt.storage.v2018_02_01.operations.BlobContainersOperations>` * 2018-03-01-preview: :class:`BlobContainersOperations<azure.mgmt.storage.v2018_03_01_preview.operations.BlobContainersOperations>` * 2018-07-01: :class:`BlobContainersOperations<azure.mgmt.storage.v2018_07_01.operations.BlobContainersOperations>` """ api_version = self._get_api_version('blob_containers') if api_version == '2018-02-01': from .v2018_02_01.operations import BlobContainersOperations as OperationClass elif api_version == '2018-03-01-preview': from .v2018_03_01_preview.operations import BlobContainersOperations as OperationClass elif api_version == '2018-07-01': from .v2018_07_01.operations import BlobContainersOperations as OperationClass else: raise NotImplementedError("APIVersion {} is not available".format(api_version)) return OperationClass(self._client, self.config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)))
Instance depends on the API version:
def blob_services(self): """Instance depends on the API version: * 2018-07-01: :class:`BlobServicesOperations<azure.mgmt.storage.v2018_07_01.operations.BlobServicesOperations>` """ api_version = self._get_api_version('blob_services') if api_version == '2018-07-01': from .v2018_07_01.operations import BlobServicesOperations as OperationClass else: raise NotImplementedError("APIVersion {} is not available".format(api_version)) return OperationClass(self._client, self.config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)))
Instance depends on the API version:
def management_policies(self): """Instance depends on the API version: * 2018-07-01: :class:`ManagementPoliciesOperations<azure.mgmt.storage.v2018_07_01.operations.ManagementPoliciesOperations>` """ api_version = self._get_api_version('management_policies') if api_version == '2018-07-01': from .v2018_07_01.operations import ManagementPoliciesOperations as OperationClass else: raise NotImplementedError("APIVersion {} is not available".format(api_version)) return OperationClass(self._client, self.config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)))
Instance depends on the API version:
def skus(self): """Instance depends on the API version: * 2017-06-01: :class:`SkusOperations<azure.mgmt.storage.v2017_06_01.operations.SkusOperations>` * 2017-10-01: :class:`SkusOperations<azure.mgmt.storage.v2017_10_01.operations.SkusOperations>` * 2018-02-01: :class:`SkusOperations<azure.mgmt.storage.v2018_02_01.operations.SkusOperations>` * 2018-03-01-preview: :class:`SkusOperations<azure.mgmt.storage.v2018_03_01_preview.operations.SkusOperations>` * 2018-07-01: :class:`SkusOperations<azure.mgmt.storage.v2018_07_01.operations.SkusOperations>` """ api_version = self._get_api_version('skus') if api_version == '2017-06-01': from .v2017_06_01.operations import SkusOperations as OperationClass elif api_version == '2017-10-01': from .v2017_10_01.operations import SkusOperations as OperationClass elif api_version == '2018-02-01': from .v2018_02_01.operations import SkusOperations as OperationClass elif api_version == '2018-03-01-preview': from .v2018_03_01_preview.operations import SkusOperations as OperationClass elif api_version == '2018-07-01': from .v2018_07_01.operations import SkusOperations as OperationClass else: raise NotImplementedError("APIVersion {} is not available".format(api_version)) return OperationClass(self._client, self.config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)))
Instance depends on the API version:
def storage_accounts(self): """Instance depends on the API version: * 2015-06-15: :class:`StorageAccountsOperations<azure.mgmt.storage.v2015_06_15.operations.StorageAccountsOperations>` * 2016-01-01: :class:`StorageAccountsOperations<azure.mgmt.storage.v2016_01_01.operations.StorageAccountsOperations>` * 2016-12-01: :class:`StorageAccountsOperations<azure.mgmt.storage.v2016_12_01.operations.StorageAccountsOperations>` * 2017-06-01: :class:`StorageAccountsOperations<azure.mgmt.storage.v2017_06_01.operations.StorageAccountsOperations>` * 2017-10-01: :class:`StorageAccountsOperations<azure.mgmt.storage.v2017_10_01.operations.StorageAccountsOperations>` * 2018-02-01: :class:`StorageAccountsOperations<azure.mgmt.storage.v2018_02_01.operations.StorageAccountsOperations>` * 2018-03-01-preview: :class:`StorageAccountsOperations<azure.mgmt.storage.v2018_03_01_preview.operations.StorageAccountsOperations>` * 2018-07-01: :class:`StorageAccountsOperations<azure.mgmt.storage.v2018_07_01.operations.StorageAccountsOperations>` """ api_version = self._get_api_version('storage_accounts') if api_version == '2015-06-15': from .v2015_06_15.operations import StorageAccountsOperations as OperationClass elif api_version == '2016-01-01': from .v2016_01_01.operations import StorageAccountsOperations as OperationClass elif api_version == '2016-12-01': from .v2016_12_01.operations import StorageAccountsOperations as OperationClass elif api_version == '2017-06-01': from .v2017_06_01.operations import StorageAccountsOperations as OperationClass elif api_version == '2017-10-01': from .v2017_10_01.operations import StorageAccountsOperations as OperationClass elif api_version == '2018-02-01': from .v2018_02_01.operations import StorageAccountsOperations as OperationClass elif api_version == '2018-03-01-preview': from .v2018_03_01_preview.operations import StorageAccountsOperations as OperationClass elif api_version == '2018-07-01': from .v2018_07_01.operations import StorageAccountsOperations as OperationClass else: raise NotImplementedError("APIVersion {} is not available".format(api_version)) return OperationClass(self._client, self.config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)))
Instance depends on the API version:
def usage(self): """Instance depends on the API version: * 2015-06-15: :class:`UsageOperations<azure.mgmt.storage.v2015_06_15.operations.UsageOperations>` * 2016-01-01: :class:`UsageOperations<azure.mgmt.storage.v2016_01_01.operations.UsageOperations>` * 2016-12-01: :class:`UsageOperations<azure.mgmt.storage.v2016_12_01.operations.UsageOperations>` * 2017-06-01: :class:`UsageOperations<azure.mgmt.storage.v2017_06_01.operations.UsageOperations>` * 2017-10-01: :class:`UsageOperations<azure.mgmt.storage.v2017_10_01.operations.UsageOperations>` * 2018-02-01: :class:`UsageOperations<azure.mgmt.storage.v2018_02_01.operations.UsageOperations>` """ api_version = self._get_api_version('usage') if api_version == '2015-06-15': from .v2015_06_15.operations import UsageOperations as OperationClass elif api_version == '2016-01-01': from .v2016_01_01.operations import UsageOperations as OperationClass elif api_version == '2016-12-01': from .v2016_12_01.operations import UsageOperations as OperationClass elif api_version == '2017-06-01': from .v2017_06_01.operations import UsageOperations as OperationClass elif api_version == '2017-10-01': from .v2017_10_01.operations import UsageOperations as OperationClass elif api_version == '2018-02-01': from .v2018_02_01.operations import UsageOperations as OperationClass else: raise NotImplementedError("APIVersion {} is not available".format(api_version)) return OperationClass(self._client, self.config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)))
Instance depends on the API version:
def usages(self): """Instance depends on the API version: * 2018-03-01-preview: :class:`UsagesOperations<azure.mgmt.storage.v2018_03_01_preview.operations.UsagesOperations>` * 2018-07-01: :class:`UsagesOperations<azure.mgmt.storage.v2018_07_01.operations.UsagesOperations>` """ api_version = self._get_api_version('usages') if api_version == '2018-03-01-preview': from .v2018_03_01_preview.operations import UsagesOperations as OperationClass elif api_version == '2018-07-01': from .v2018_07_01.operations import UsagesOperations as OperationClass else: raise NotImplementedError("APIVersion {} is not available".format(api_version)) return OperationClass(self._client, self.config, Serializer(self._models_dict(api_version)), Deserializer(self._models_dict(api_version)))
Module depends on the API version:
def models(cls, api_version=DEFAULT_API_VERSION): """Module depends on the API version: * 2016-06-01: :mod:`v2016_06_01.models<azure.mgmt.resource.subscriptions.v2016_06_01.models>` """ if api_version == '2016-06-01': from .v2016_06_01 import models return models raise NotImplementedError("APIVersion {} is not available".format(api_version))
Create a Service Bus client from a connection string.
def from_connection_string(cls, conn_str, *, loop=None, **kwargs): """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. """ address, policy, key, _ = parse_conn_str(conn_str) parsed_namespace = urlparse(address) namespace, _, base = parsed_namespace.hostname.partition('.') return cls( service_namespace=namespace, shared_access_key_name=policy, shared_access_key_value=key, host_base='.' + base, loop=loop, **kwargs)
Get an async client for a subscription entity.
def get_subscription(self, topic_name, subscription_name): """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: subscription = self.mgmt_client.get_subscription(topic_name, subscription_name) except requests.exceptions.ConnectionError as e: raise ServiceBusConnectionError("Namespace: {} not found".format(self.service_namespace), e) except AzureServiceBusResourceNotFound: raise ServiceBusResourceNotFound("Specificed subscription does not exist.") return SubscriptionClient.from_entity( self._get_host(), topic_name, subscription, shared_access_key_name=self.shared_access_key_name, shared_access_key_value=self.shared_access_key_value, loop=self.loop, debug=self.debug)
Get an async client for all subscription entities in the topic.
def list_subscriptions(self, topic_name): """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. """ try: subs = self.mgmt_client.list_subscriptions(topic_name) except requests.exceptions.ConnectionError as e: raise ServiceBusConnectionError("Namespace: {} not found".format(self.service_namespace), e) except AzureServiceBusResourceNotFound: raise ServiceBusResourceNotFound("Specificed topic does not exist.") sub_clients = [] for sub in subs: sub_clients.append(SubscriptionClient.from_entity( self._get_host(), topic_name, sub, shared_access_key_name=self.shared_access_key_name, shared_access_key_value=self.shared_access_key_value, loop=self.loop, debug=self.debug)) return sub_clients
Send one or more messages to the current entity.
async def send(self, messages, message_timeout=0, session=None, **kwargs): """Send one or more messages to the current entity. This operation will open a single-use connection, send the supplied messages, and close connection. If the entity requires sessions, a session ID must be either provided here, or set on each outgoing message. :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. """ async with self.get_sender(message_timeout=message_timeout, session=session, **kwargs) as sender: if isinstance(messages, Message): sender.queue_message(messages) else: try: messages = list(messages) except TypeError: raise TypeError( "Value of messages must be a 'Message' object or a synchronous iterable of 'Message' objects.") for m in messages: if not isinstance(m, Message): raise TypeError("Item in iterator is not of type 'Message'.") sender.queue_message(m) return await sender.send_pending_messages()
Get a Sender for the Service Bus endpoint.
def get_sender(self, message_timeout=0, session=None, **kwargs): """Get a Sender for the Service Bus endpoint. A Sender represents a single open connection within which multiple send operations can be made. :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. """ handler_id = str(uuid.uuid4()) if self.entity and self.requires_session: return SessionSender( handler_id, self.entity_uri, self.auth_config, session=session, loop=self.loop, debug=self.debug, msg_timeout=message_timeout, **kwargs) return Sender( handler_id, self.entity_uri, self.auth_config, session=session, loop=self.loop, debug=self.debug, msg_timeout=message_timeout, **kwargs)
Get a Receiver for the Service Bus endpoint.
def get_receiver(self, session=None, prefetch=0, mode=ReceiveSettleMode.PeekLock, idle_timeout=0, **kwargs): """Get a Receiver for the Service Bus endpoint. A Receiver represents a single open connection with which multiple receive operations can be made. :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 self.entity and not self.requires_session and session: raise ValueError("A session cannot be used with a non-sessionful entitiy.") if self.entity and self.requires_session and not session: raise ValueError("This entity requires a session.") if int(prefetch) < 0 or int(prefetch) > 50000: raise ValueError("Prefetch must be an integer between 0 and 50000 inclusive.") prefetch += 1 handler_id = str(uuid.uuid4()) if session: return SessionReceiver( handler_id, self.entity_uri, self.auth_config, session=session, loop=self.loop, debug=self.debug, timeout=int(idle_timeout * 1000), prefetch=prefetch, mode=mode, **kwargs) return Receiver( handler_id, self.entity_uri, self.auth_config, loop=self.loop, debug=self.debug, timeout=int(idle_timeout * 1000), prefetch=prefetch, mode=mode, **kwargs)
Get a Receiver for the deadletter endpoint of the entity.
def get_deadletter_receiver( self, transfer_deadletter=False, prefetch=0, mode=ReceiveSettleMode.PeekLock, idle_timeout=0, **kwargs): """Get a Receiver for the deadletter endpoint of the entity. A Receiver represents a single open connection with which multiple receive operations can be made. :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. """ if int(prefetch) < 0 or int(prefetch) > 50000: raise ValueError("Prefetch must be an integer between 0 and 50000 inclusive.") prefetch += 1 handler_id = str(uuid.uuid4()) if transfer_deadletter: entity_uri = self.mgmt_client.format_transfer_dead_letter_queue_name(self.entity_uri) else: entity_uri = self.mgmt_client.format_dead_letter_queue_name(self.entity_uri) return Receiver( handler_id, entity_uri, self.auth_config, loop=self.loop, debug=self.debug, timeout=int(idle_timeout * 1000), prefetch=prefetch, mode=mode, **kwargs)
Extracts request id from response header.
def parse_response_for_async_op(response): ''' Extracts request id from response header. ''' if response is None: return None result = AsynchronousOperationResult() if response.headers: for name, value in response.headers: if name.lower() == 'x-ms-request-id': result.request_id = value return result
Returns a new service which will process requests with the specified filter. Filtering operations can include logging automatic retrying etc... The filter is a lambda which receives the HTTPRequest and another lambda. The filter can perform any pre - processing on the request pass it off to the next lambda and then perform any post - processing on the response.
def with_filter(self, filter): '''Returns a new service which will process requests with the specified filter. Filtering operations can include logging, automatic retrying, etc... The filter is a lambda which receives the HTTPRequest and another lambda. The filter can perform any pre-processing on the request, pass it off to the next lambda, and then perform any post-processing on the response.''' res = type(self)(self.subscription_id, self.cert_file, self.host, self.request_session, self._httpclient.timeout) old_filter = self._filter def new_filter(request): return filter(request, old_filter) res._filter = new_filter return res
Sets the proxy server host and port for the HTTP CONNECT Tunnelling.
def set_proxy(self, host, port, user=None, password=None): ''' Sets the proxy server host and port for the HTTP CONNECT Tunnelling. host: Address of the proxy. Ex: '192.168.0.100' port: Port of the proxy. Ex: 6000 user: User for proxy authorization. password: Password for proxy authorization. ''' self._httpclient.set_proxy(host, port, user, password)
Performs a GET request and returns the response.
def perform_get(self, path, x_ms_version=None): ''' Performs a GET request and returns the response. path: Path to the resource. Ex: '/<subscription-id>/services/hostedservices/<service-name>' x_ms_version: If specified, this is used for the x-ms-version header. Otherwise, self.x_ms_version is used. ''' request = HTTPRequest() request.method = 'GET' request.host = self.host request.path = path request.path, request.query = self._httpclient._update_request_uri_query(request) request.headers = self._update_management_header(request, x_ms_version) response = self._perform_request(request) return response
Performs a PUT request and returns the response.
def perform_put(self, path, body, x_ms_version=None): ''' Performs a PUT request and returns the response. path: Path to the resource. Ex: '/<subscription-id>/services/hostedservices/<service-name>' body: Body for the PUT request. x_ms_version: If specified, this is used for the x-ms-version header. Otherwise, self.x_ms_version is used. ''' request = HTTPRequest() request.method = 'PUT' request.host = self.host request.path = path request.body = _get_request_body(body) request.path, request.query = self._httpclient._update_request_uri_query(request) request.headers = self._update_management_header(request, x_ms_version) response = self._perform_request(request) return response
Waits for an asynchronous operation to complete.
def wait_for_operation_status(self, request_id, wait_for_status='Succeeded', timeout=30, sleep_interval=5, progress_callback=wait_for_operation_status_progress_default_callback, success_callback=wait_for_operation_status_success_default_callback, failure_callback=wait_for_operation_status_failure_default_callback): ''' Waits for an asynchronous operation to complete. This calls get_operation_status in a loop and returns when the expected status is reached. The result of get_operation_status is returned. By default, an exception is raised on timeout or error status. request_id: The request ID for the request you wish to track. wait_for_status: Status to wait for. Default is 'Succeeded'. timeout: Total timeout in seconds. Default is 30s. sleep_interval: Sleep time in seconds for each iteration. Default is 5s. progress_callback: Callback for each iteration. Default prints '.'. Set it to None for no progress notification. success_callback: Callback on success. Default prints newline. Set it to None for no success notification. failure_callback: Callback on failure. Default prints newline+error details then raises exception. Set it to None for no failure notification. ''' loops = timeout // sleep_interval + 1 start_time = time.time() for _ in range(int(loops)): result = self.get_operation_status(request_id) elapsed = time.time() - start_time if result.status == wait_for_status: if success_callback is not None: success_callback(elapsed) return result elif result.error: if failure_callback is not None: ex = AzureAsyncOperationHttpError(_ERROR_ASYNC_OP_FAILURE, result.status, result) failure_callback(elapsed, ex) return result else: if progress_callback is not None: progress_callback(elapsed) time.sleep(sleep_interval) if failure_callback is not None: ex = AzureAsyncOperationHttpError(_ERROR_ASYNC_OP_TIMEOUT, result.status, result) failure_callback(elapsed, ex) return result
Returns the status of the specified operation. After calling an asynchronous operation you can call Get Operation Status to determine whether the operation has succeeded failed or is still in progress.
def get_operation_status(self, request_id): ''' Returns the status of the specified operation. After calling an asynchronous operation, you can call Get Operation Status to determine whether the operation has succeeded, failed, or is still in progress. request_id: The request ID for the request you wish to track. ''' _validate_not_none('request_id', request_id) return self._perform_get( '/' + self.subscription_id + '/operations/' + _str(request_id), Operation)
Add additional headers for management.
def _update_management_header(self, request, x_ms_version): ''' Add additional headers for management. ''' if request.method in ['PUT', 'POST', 'MERGE', 'DELETE']: request.headers.append(('Content-Length', str(len(request.body)))) # append additional headers base on the service request.headers.append(('x-ms-version', x_ms_version or self.x_ms_version)) # if it is not GET or HEAD request, must set content-type. if not request.method in ['GET', 'HEAD']: for name, _ in request.headers: if 'content-type' == name.lower(): break else: request.headers.append( ('Content-Type', self.content_type)) return request.headers
Assumed called on Travis to prepare a package to be deployed
def travis_build_package(): """Assumed called on Travis, to prepare a package to be deployed This method prints on stdout for Travis. Return is obj to pass to sys.exit() directly """ travis_tag = os.environ.get('TRAVIS_TAG') if not travis_tag: print("TRAVIS_TAG environment variable is not present") return "TRAVIS_TAG environment variable is not present" try: name, version = travis_tag.split("_") except ValueError: print("TRAVIS_TAG is not '<package_name>_<version>' (tag is: {})".format(travis_tag)) return "TRAVIS_TAG is not '<package_name>_<version>' (tag is: {})".format(travis_tag) try: version = Version(version) except InvalidVersion: print("Version must be a valid PEP440 version (version is: {})".format(version)) return "Version must be a valid PEP440 version (version is: {})".format(version) if name.lower() in OMITTED_RELEASE_PACKAGES: print("The input package {} has been disabled for release from Travis.CI.".format(name)) return abs_dist_path = Path(os.environ['TRAVIS_BUILD_DIR'], 'dist') create_package(name, str(abs_dist_path)) print("Produced:\n{}".format(list(abs_dist_path.glob('*')))) pattern = "*{}*".format(version) packages = list(abs_dist_path.glob(pattern)) if not packages: return "Package version does not match tag {}, abort".format(version) pypi_server = os.environ.get("PYPI_SERVER", "default PyPI server") print("Package created as expected and will be pushed to {}".format(pypi_server))
List certificates in a specified key vault.
def get_certificates( self, vault_base_url, maxresults=None, include_pending=None, custom_headers=None, raw=False, **operation_config): """List certificates in a specified key vault. The GetCertificates operation returns the set of certificates resources in the specified key vault. This operation requires the certificates/list permission. :param vault_base_url: The vault name, for example https://myvault.vault.azure.net. :type vault_base_url: str :param maxresults: Maximum number of results to return in a page. If not specified the service will return up to 25 results. :type maxresults: int :param include_pending: Specifies whether to include certificates which are not completely provisioned. :type include_pending: bool :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 CertificateItem :rtype: ~azure.keyvault.v7_0.models.CertificateItemPaged[~azure.keyvault.v7_0.models.CertificateItem] :raises: :class:`KeyVaultErrorException<azure.keyvault.v7_0.models.KeyVaultErrorException>` """ def internal_paging(next_link=None, raw=False): if not next_link: # Construct URL url = self.get_certificates.metadata['url'] path_format_arguments = { 'vaultBaseUrl': self._serialize.url("vault_base_url", vault_base_url, 'str', skip_quote=True) } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} if maxresults is not None: query_parameters['maxresults'] = self._serialize.query("maxresults", maxresults, 'int', maximum=25, minimum=1) if include_pending is not None: query_parameters['includePending'] = self._serialize.query("include_pending", include_pending, 'bool') query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') else: url = next_link query_parameters = {} # Construct headers header_parameters = {} header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct and send request request = self._client.get(url, query_parameters) response = self._client.send( request, header_parameters, stream=False, **operation_config) if response.status_code not in [200]: raise models.KeyVaultErrorException(self._deserialize, response) return response # Deserialize response deserialized = models.CertificateItemPaged(internal_paging, self._deserialize.dependencies) if raw: header_dict = {} client_raw_response = models.CertificateItemPaged(internal_paging, self._deserialize.dependencies, header_dict) return client_raw_response return deserialized
Get list of available service bus regions.
def get_regions(self): ''' Get list of available service bus regions. ''' response = self._perform_get( self._get_path('services/serviceBus/Regions/', None), None) return _MinidomXmlToObject.convert_response_to_feeds( response, _ServiceBusManagementXmlSerializer.xml_to_region)
List the service bus namespaces defined on the account.
def list_namespaces(self): ''' List the service bus namespaces defined on the account. ''' response = self._perform_get( self._get_path('services/serviceBus/Namespaces/', None), None) return _MinidomXmlToObject.convert_response_to_feeds( response, _ServiceBusManagementXmlSerializer.xml_to_namespace)
Get details about a specific namespace.
def get_namespace(self, name): ''' Get details about a specific namespace. name: Name of the service bus namespace. ''' response = self._perform_get( self._get_path('services/serviceBus/Namespaces', name), None) return _ServiceBusManagementXmlSerializer.xml_to_namespace( response.body)
Create a new service bus namespace.
def create_namespace(self, name, region): ''' Create a new service bus namespace. name: Name of the service bus namespace to create. region: Region to create the namespace in. ''' _validate_not_none('name', name) return self._perform_put( self._get_path('services/serviceBus/Namespaces', name), _ServiceBusManagementXmlSerializer.namespace_to_xml(region))
Delete a service bus namespace.
def delete_namespace(self, name): ''' Delete a service bus namespace. name: Name of the service bus namespace to delete. ''' _validate_not_none('name', name) return self._perform_delete( self._get_path('services/serviceBus/Namespaces', name), None)
Checks to see if the specified service bus namespace is available or if it has already been taken.
def check_namespace_availability(self, name): ''' Checks to see if the specified service bus namespace is available, or if it has already been taken. name: Name of the service bus namespace to validate. ''' _validate_not_none('name', name) response = self._perform_get( self._get_path('services/serviceBus/CheckNamespaceAvailability', None) + '/?namespace=' + _str(name), None) return _ServiceBusManagementXmlSerializer.xml_to_namespace_availability( response.body)
Enumerates the queues in the service namespace.
def list_queues(self, name): ''' Enumerates the queues in the service namespace. name: Name of the service bus namespace. ''' _validate_not_none('name', name) response = self._perform_get( self._get_list_queues_path(name), None) return _MinidomXmlToObject.convert_response_to_feeds( response, partial( _MinidomXmlToObject.convert_xml_to_azure_object, azure_type=QueueDescription ) )
Retrieves the topics in the service namespace.
def list_topics(self, name): ''' Retrieves the topics in the service namespace. name: Name of the service bus namespace. ''' response = self._perform_get( self._get_list_topics_path(name), None) return _MinidomXmlToObject.convert_response_to_feeds( response, partial( _MinidomXmlToObject.convert_xml_to_azure_object, azure_type=TopicDescription ) )
Retrieves the notification hubs in the service namespace.
def list_notification_hubs(self, name): ''' Retrieves the notification hubs in the service namespace. name: Name of the service bus namespace. ''' response = self._perform_get( self._get_list_notification_hubs_path(name), None) return _MinidomXmlToObject.convert_response_to_feeds( response, partial( _MinidomXmlToObject.convert_xml_to_azure_object, azure_type=NotificationHubDescription ) )
Retrieves the relays in the service namespace.
def list_relays(self, name): ''' Retrieves the relays in the service namespace. name: Name of the service bus namespace. ''' response = self._perform_get( self._get_list_relays_path(name), None) return _MinidomXmlToObject.convert_response_to_feeds( response, partial( _MinidomXmlToObject.convert_xml_to_azure_object, azure_type=RelayDescription ) )
Retrieves the list of supported metrics for this namespace and queue
def get_supported_metrics_queue(self, name, queue_name): ''' Retrieves the list of supported metrics for this namespace and queue name: Name of the service bus namespace. queue_name: Name of the service bus queue in this namespace. ''' response = self._perform_get( self._get_get_supported_metrics_queue_path(name, queue_name), None) return _MinidomXmlToObject.convert_response_to_feeds( response, partial( _ServiceBusManagementXmlSerializer.xml_to_metrics, object_type=MetricProperties ) )
Retrieves the list of supported metrics for this namespace and topic
def get_supported_metrics_topic(self, name, topic_name): ''' Retrieves the list of supported metrics for this namespace and topic name: Name of the service bus namespace. topic_name: Name of the service bus queue in this namespace. ''' response = self._perform_get( self._get_get_supported_metrics_topic_path(name, topic_name), None) return _MinidomXmlToObject.convert_response_to_feeds( response, partial( _ServiceBusManagementXmlSerializer.xml_to_metrics, object_type=MetricProperties ) )
Retrieves the list of supported metrics for this namespace and topic
def get_supported_metrics_notification_hub(self, name, hub_name): ''' Retrieves the list of supported metrics for this namespace and topic name: Name of the service bus namespace. hub_name: Name of the service bus notification hub in this namespace. ''' response = self._perform_get( self._get_get_supported_metrics_hub_path(name, hub_name), None) return _MinidomXmlToObject.convert_response_to_feeds( response, partial( _ServiceBusManagementXmlSerializer.xml_to_metrics, object_type=MetricProperties ) )
Retrieves the list of supported metrics for this namespace and relay
def get_supported_metrics_relay(self, name, relay_name): ''' Retrieves the list of supported metrics for this namespace and relay name: Name of the service bus namespace. relay_name: Name of the service bus relay in this namespace. ''' response = self._perform_get( self._get_get_supported_metrics_relay_path(name, relay_name), None) return _MinidomXmlToObject.convert_response_to_feeds( response, partial( _ServiceBusManagementXmlSerializer.xml_to_metrics, object_type=MetricProperties ) )
Retrieves the list of supported metrics for this namespace and queue
def get_metrics_data_queue(self, name, queue_name, metric, rollup, filter_expresssion): ''' Retrieves the list of supported metrics for this namespace and queue name: Name of the service bus namespace. queue_name: Name of the service bus queue in this namespace. metric: name of a supported metric rollup: name of a supported rollup filter_expression: filter, for instance "$filter=Timestamp gt datetime'2014-10-01T00:00:00Z'" ''' response = self._perform_get( self._get_get_metrics_data_queue_path(name, queue_name, metric, rollup, filter_expresssion), None) return _MinidomXmlToObject.convert_response_to_feeds( response, partial( _ServiceBusManagementXmlSerializer.xml_to_metrics, object_type=MetricValues ) )
Retrieves the list of supported metrics for this namespace and topic
def get_metrics_data_topic(self, name, topic_name, metric, rollup, filter_expresssion): ''' Retrieves the list of supported metrics for this namespace and topic name: Name of the service bus namespace. topic_name: Name of the service bus queue in this namespace. metric: name of a supported metric rollup: name of a supported rollup filter_expression: filter, for instance "$filter=Timestamp gt datetime'2014-10-01T00:00:00Z'" ''' response = self._perform_get( self._get_get_metrics_data_topic_path(name, topic_name, metric, rollup, filter_expresssion), None) return _MinidomXmlToObject.convert_response_to_feeds( response, partial( _ServiceBusManagementXmlSerializer.xml_to_metrics, object_type=MetricValues ) )
Retrieves the list of supported metrics for this namespace and topic
def get_metrics_data_notification_hub(self, name, hub_name, metric, rollup, filter_expresssion): ''' Retrieves the list of supported metrics for this namespace and topic name: Name of the service bus namespace. hub_name: Name of the service bus notification hub in this namespace. metric: name of a supported metric rollup: name of a supported rollup filter_expression: filter, for instance "$filter=Timestamp gt datetime'2014-10-01T00:00:00Z'" ''' response = self._perform_get( self._get_get_metrics_data_hub_path(name, hub_name, metric, rollup, filter_expresssion), None) return _MinidomXmlToObject.convert_response_to_feeds( response, partial( _ServiceBusManagementXmlSerializer.xml_to_metrics, object_type=MetricValues ) )
Retrieves the list of supported metrics for this namespace and relay
def get_metrics_data_relay(self, name, relay_name, metric, rollup, filter_expresssion): ''' Retrieves the list of supported metrics for this namespace and relay name: Name of the service bus namespace. relay_name: Name of the service bus relay in this namespace. metric: name of a supported metric rollup: name of a supported rollup filter_expression: filter, for instance "$filter=Timestamp gt datetime'2014-10-01T00:00:00Z'" ''' response = self._perform_get( self._get_get_metrics_data_relay_path(name, relay_name, metric, rollup, filter_expresssion), None) return _MinidomXmlToObject.convert_response_to_feeds( response, partial( _ServiceBusManagementXmlSerializer.xml_to_metrics, object_type=MetricValues ) )
This operation gets rollup data for Service Bus metrics queue. Rollup data includes the time granularity for the telemetry aggregation as well as the retention settings for each time granularity.
def get_metrics_rollups_queue(self, name, queue_name, metric): ''' This operation gets rollup data for Service Bus metrics queue. Rollup data includes the time granularity for the telemetry aggregation as well as the retention settings for each time granularity. name: Name of the service bus namespace. queue_name: Name of the service bus queue in this namespace. metric: name of a supported metric ''' response = self._perform_get( self._get_get_metrics_rollup_queue_path(name, queue_name, metric), None) return _MinidomXmlToObject.convert_response_to_feeds( response, partial( _ServiceBusManagementXmlSerializer.xml_to_metrics, object_type=MetricRollups ) )
This operation gets rollup data for Service Bus metrics topic. Rollup data includes the time granularity for the telemetry aggregation as well as the retention settings for each time granularity.
def get_metrics_rollups_topic(self, name, topic_name, metric): ''' This operation gets rollup data for Service Bus metrics topic. Rollup data includes the time granularity for the telemetry aggregation as well as the retention settings for each time granularity. name: Name of the service bus namespace. topic_name: Name of the service bus queue in this namespace. metric: name of a supported metric ''' response = self._perform_get( self._get_get_metrics_rollup_topic_path(name, topic_name, metric), None) return _MinidomXmlToObject.convert_response_to_feeds( response, partial( _ServiceBusManagementXmlSerializer.xml_to_metrics, object_type=MetricRollups ) )
This operation gets rollup data for Service Bus metrics notification hub. Rollup data includes the time granularity for the telemetry aggregation as well as the retention settings for each time granularity.
def get_metrics_rollups_notification_hub(self, name, hub_name, metric): ''' This operation gets rollup data for Service Bus metrics notification hub. Rollup data includes the time granularity for the telemetry aggregation as well as the retention settings for each time granularity. name: Name of the service bus namespace. hub_name: Name of the service bus notification hub in this namespace. metric: name of a supported metric ''' response = self._perform_get( self._get_get_metrics_rollup_hub_path(name, hub_name, metric), None) return _MinidomXmlToObject.convert_response_to_feeds( response, partial( _ServiceBusManagementXmlSerializer.xml_to_metrics, object_type=MetricRollups ) )
This operation gets rollup data for Service Bus metrics relay. Rollup data includes the time granularity for the telemetry aggregation as well as the retention settings for each time granularity.
def get_metrics_rollups_relay(self, name, relay_name, metric): ''' This operation gets rollup data for Service Bus metrics relay. Rollup data includes the time granularity for the telemetry aggregation as well as the retention settings for each time granularity. name: Name of the service bus namespace. relay_name: Name of the service bus relay in this namespace. metric: name of a supported metric ''' response = self._perform_get( self._get_get_metrics_rollup_relay_path(name, relay_name, metric), None) return _MinidomXmlToObject.convert_response_to_feeds( response, partial( _ServiceBusManagementXmlSerializer.xml_to_metrics, object_type=MetricRollups ) )
Create a virtual environment in a directory.
def create(env_dir, system_site_packages=False, clear=False, symlinks=False, with_pip=False, prompt=None): """Create a virtual environment in a directory.""" builder = ExtendedEnvBuilder(system_site_packages=system_site_packages, clear=clear, symlinks=symlinks, with_pip=with_pip, prompt=prompt) builder.create(env_dir) return builder.context
Create a venv with these packages in a temp dir and yielf the env.
def create_venv_with_package(packages): """Create a venv with these packages in a temp dir and yielf the env. packages should be an iterable of pip version instructio (e.g. package~=1.2.3) """ with tempfile.TemporaryDirectory() as tempdir: myenv = create(tempdir, with_pip=True) pip_call = [ myenv.env_exe, "-m", "pip", "install", ] subprocess.check_call(pip_call + ['-U', 'pip']) if packages: subprocess.check_call(pip_call + packages) yield myenv
This operation generates a thumbnail image with the user - specified width and height. By default the service analyzes the image identifies the region of interest ( ROI ) and generates smart cropping coordinates based on the ROI. Smart cropping helps when you specify an aspect ratio that differs from that of the input image. A successful response contains the thumbnail image binary. If the request failed the response contains an error code and a message to help determine what went wrong. Upon failure the error code and an error message are returned. The error code could be one of InvalidImageUrl InvalidImageFormat InvalidImageSize InvalidThumbnailSize NotSupportedImage FailedToProcess Timeout or InternalServerError.
def generate_thumbnail_in_stream( self, width, height, image, smart_cropping=False, custom_headers=None, raw=False, callback=None, **operation_config): """This operation generates a thumbnail image with the user-specified width and height. By default, the service analyzes the image, identifies the region of interest (ROI), and generates smart cropping coordinates based on the ROI. Smart cropping helps when you specify an aspect ratio that differs from that of the input image. A successful response contains the thumbnail image binary. If the request failed, the response contains an error code and a message to help determine what went wrong. Upon failure, the error code and an error message are returned. The error code could be one of InvalidImageUrl, InvalidImageFormat, InvalidImageSize, InvalidThumbnailSize, NotSupportedImage, FailedToProcess, Timeout, or InternalServerError. :param width: Width of the thumbnail, in pixels. It must be between 1 and 1024. Recommended minimum of 50. :type width: int :param height: Height of the thumbnail, in pixels. It must be between 1 and 1024. Recommended minimum of 50. :type height: int :param image: An image stream. :type image: Generator :param smart_cropping: Boolean flag for enabling smart cropping. :type smart_cropping: bool :param dict custom_headers: headers that will be added to the request :param bool raw: returns the direct response alongside the deserialized response :param callback: When specified, will be called with each chunk of data that is streamed. The callback should take two arguments, the bytes of the current chunk of data and the response object. If the data is uploading, response will be None. :type callback: Callable[Bytes, response=None] :param operation_config: :ref:`Operation configuration overrides<msrest:optionsforoperations>`. :return: object or ClientRawResponse if raw=true :rtype: Generator or ~msrest.pipeline.ClientRawResponse :raises: :class:`HttpOperationError<msrest.exceptions.HttpOperationError>` """ # Construct URL url = self.generate_thumbnail_in_stream.metadata['url'] path_format_arguments = { 'Endpoint': self._serialize.url("self.config.endpoint", self.config.endpoint, 'str', skip_quote=True) } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['width'] = self._serialize.query("width", width, 'int', maximum=1024, minimum=1) query_parameters['height'] = self._serialize.query("height", height, 'int', maximum=1024, minimum=1) if smart_cropping is not None: query_parameters['smartCropping'] = self._serialize.query("smart_cropping", smart_cropping, 'bool') # Construct headers header_parameters = {} header_parameters['Accept'] = 'application/octet-stream' header_parameters['Content-Type'] = 'application/octet-stream' if custom_headers: header_parameters.update(custom_headers) # Construct body body_content = self._client.stream_upload(image, callback) # Construct and send request request = self._client.post(url, query_parameters, header_parameters, body_content) response = self._client.send(request, stream=True, **operation_config) if response.status_code not in [200]: raise HttpOperationError(self._deserialize, response) deserialized = None if response.status_code == 200: deserialized = self._client.stream_download(response, callback) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized
Create a new Azure SQL Database server.
def create_server(self, admin_login, admin_password, location): ''' Create a new Azure SQL Database server. admin_login: The administrator login name for the new server. admin_password: The administrator login password for the new server. location: The region to deploy the new server. ''' _validate_not_none('admin_login', admin_login) _validate_not_none('admin_password', admin_password) _validate_not_none('location', location) response = self.perform_post( self._get_servers_path(), _SqlManagementXmlSerializer.create_server_to_xml( admin_login, admin_password, location ) ) return _SqlManagementXmlSerializer.xml_to_create_server_response( response.body)
Reset the administrator password for a server.
def set_server_admin_password(self, server_name, admin_password): ''' Reset the administrator password for a server. server_name: Name of the server to change the password. admin_password: The new administrator password for the server. ''' _validate_not_none('server_name', server_name) _validate_not_none('admin_password', admin_password) return self._perform_post( self._get_servers_path(server_name) + '?op=ResetPassword', _SqlManagementXmlSerializer.set_server_admin_password_to_xml( admin_password ) )
Deletes an Azure SQL Database server ( including all its databases ).
def delete_server(self, server_name): ''' Deletes an Azure SQL Database server (including all its databases). server_name: Name of the server you want to delete. ''' _validate_not_none('server_name', server_name) return self._perform_delete( self._get_servers_path(server_name))
Gets quotas for an Azure SQL Database Server.
def list_quotas(self, server_name): ''' Gets quotas for an Azure SQL Database Server. server_name: Name of the server. ''' _validate_not_none('server_name', server_name) response = self._perform_get(self._get_quotas_path(server_name), None) return _MinidomXmlToObject.parse_service_resources_response( response, ServerQuota)
Gets the event logs for an Azure SQL Database Server.
def get_server_event_logs(self, server_name, start_date, interval_size_in_minutes, event_types=''): ''' Gets the event logs for an Azure SQL Database Server. server_name: Name of the server to retrieve the event logs from. start_date: The starting date and time of the events to retrieve in UTC format, for example '2011-09-28 16:05:00'. interval_size_in_minutes: Size of the event logs to retrieve (in minutes). Valid values are: 5, 60, or 1440. event_types: The event type of the log entries you want to retrieve. Valid values are: - connection_successful - connection_failed - connection_terminated - deadlock - throttling - throttling_long_transaction To return all event types pass in an empty string. ''' _validate_not_none('server_name', server_name) _validate_not_none('start_date', start_date) _validate_not_none('interval_size_in_minutes', interval_size_in_minutes) _validate_not_none('event_types', event_types) path = self._get_server_event_logs_path(server_name) + \ '?startDate={0}&intervalSizeInMinutes={1}&eventTypes={2}'.format( start_date, interval_size_in_minutes, event_types) response = self._perform_get(path, None) return _MinidomXmlToObject.parse_service_resources_response( response, EventLog)
Creates an Azure SQL Database server firewall rule.
def create_firewall_rule(self, server_name, name, start_ip_address, end_ip_address): ''' Creates an Azure SQL Database server firewall rule. server_name: Name of the server to set the firewall rule on. name: The name of the new firewall rule. start_ip_address: The lowest IP address in the range of the server-level firewall setting. IP addresses equal to or greater than this can attempt to connect to the server. The lowest possible IP address is 0.0.0.0. end_ip_address: The highest IP address in the range of the server-level firewall setting. IP addresses equal to or less than this can attempt to connect to the server. The highest possible IP address is 255.255.255.255. ''' _validate_not_none('server_name', server_name) _validate_not_none('name', name) _validate_not_none('start_ip_address', start_ip_address) _validate_not_none('end_ip_address', end_ip_address) return self._perform_post( self._get_firewall_rules_path(server_name), _SqlManagementXmlSerializer.create_firewall_rule_to_xml( name, start_ip_address, end_ip_address ) )
Update a firewall rule for an Azure SQL Database server.
def update_firewall_rule(self, server_name, name, start_ip_address, end_ip_address): ''' Update a firewall rule for an Azure SQL Database server. server_name: Name of the server to set the firewall rule on. name: The name of the firewall rule to update. start_ip_address: The lowest IP address in the range of the server-level firewall setting. IP addresses equal to or greater than this can attempt to connect to the server. The lowest possible IP address is 0.0.0.0. end_ip_address: The highest IP address in the range of the server-level firewall setting. IP addresses equal to or less than this can attempt to connect to the server. The highest possible IP address is 255.255.255.255. ''' _validate_not_none('server_name', server_name) _validate_not_none('name', name) _validate_not_none('start_ip_address', start_ip_address) _validate_not_none('end_ip_address', end_ip_address) return self._perform_put( self._get_firewall_rules_path(server_name, name), _SqlManagementXmlSerializer.update_firewall_rule_to_xml( name, start_ip_address, end_ip_address ) )
Deletes an Azure SQL Database server firewall rule.
def delete_firewall_rule(self, server_name, name): ''' Deletes an Azure SQL Database server firewall rule. server_name: Name of the server with the firewall rule you want to delete. name: Name of the firewall rule you want to delete. ''' _validate_not_none('server_name', server_name) _validate_not_none('name', name) return self._perform_delete( self._get_firewall_rules_path(server_name, name))
Retrieves the set of firewall rules for an Azure SQL Database Server.
def list_firewall_rules(self, server_name): ''' Retrieves the set of firewall rules for an Azure SQL Database Server. server_name: Name of the server. ''' _validate_not_none('server_name', server_name) response = self._perform_get(self._get_firewall_rules_path(server_name), None) return _MinidomXmlToObject.parse_service_resources_response( response, FirewallRule)
Gets the service level objectives for an Azure SQL Database server.
def list_service_level_objectives(self, server_name): ''' Gets the service level objectives for an Azure SQL Database server. server_name: Name of the server. ''' _validate_not_none('server_name', server_name) response = self._perform_get( self._get_service_objectives_path(server_name), None) return _MinidomXmlToObject.parse_service_resources_response( response, ServiceObjective)
Creates a new Azure SQL Database.
def create_database(self, server_name, name, service_objective_id, edition=None, collation_name=None, max_size_bytes=None): ''' Creates a new Azure SQL Database. server_name: Name of the server to contain the new database. name: Required. The name for the new database. See Naming Requirements in Azure SQL Database General Guidelines and Limitations and Database Identifiers for more information. service_objective_id: Required. The GUID corresponding to the performance level for Edition. See List Service Level Objectives for current values. edition: Optional. The Service Tier (Edition) for the new database. If omitted, the default is Web. Valid values are Web, Business, Basic, Standard, and Premium. See Azure SQL Database Service Tiers (Editions) and Web and Business Edition Sunset FAQ for more information. collation_name: Optional. The database collation. This can be any collation supported by SQL. If omitted, the default collation is used. See SQL Server Collation Support in Azure SQL Database General Guidelines and Limitations for more information. max_size_bytes: Optional. Sets the maximum size, in bytes, for the database. This value must be within the range of allowed values for Edition. If omitted, the default value for the edition is used. See Azure SQL Database Service Tiers (Editions) for current maximum databases sizes. Convert MB or GB values to bytes. 1 MB = 1048576 bytes. 1 GB = 1073741824 bytes. ''' _validate_not_none('server_name', server_name) _validate_not_none('name', name) _validate_not_none('service_objective_id', service_objective_id) return self._perform_post( self._get_databases_path(server_name), _SqlManagementXmlSerializer.create_database_to_xml( name, service_objective_id, edition, collation_name, max_size_bytes ) )
Updates existing database details.
def update_database(self, server_name, name, new_database_name=None, service_objective_id=None, edition=None, max_size_bytes=None): ''' Updates existing database details. server_name: Name of the server to contain the new database. name: Required. The name for the new database. See Naming Requirements in Azure SQL Database General Guidelines and Limitations and Database Identifiers for more information. new_database_name: Optional. The new name for the new database. service_objective_id: Optional. The new service level to apply to the database. For more information about service levels, see Azure SQL Database Service Tiers and Performance Levels. Use List Service Level Objectives to get the correct ID for the desired service objective. edition: Optional. The new edition for the new database. max_size_bytes: Optional. The new size of the database in bytes. For information on available sizes for each edition, see Azure SQL Database Service Tiers (Editions). ''' _validate_not_none('server_name', server_name) _validate_not_none('name', name) return self._perform_put( self._get_databases_path(server_name, name), _SqlManagementXmlSerializer.update_database_to_xml( new_database_name, service_objective_id, edition, max_size_bytes ) )
Deletes an Azure SQL Database.
def delete_database(self, server_name, name): ''' Deletes an Azure SQL Database. server_name: Name of the server where the database is located. name: Name of the database to delete. ''' return self._perform_delete(self._get_databases_path(server_name, name))
List the SQL databases defined on the specified server name
def list_databases(self, name): ''' List the SQL databases defined on the specified server name ''' response = self._perform_get(self._get_list_databases_path(name), None) return _MinidomXmlToObject.parse_service_resources_response( response, Database)
Visual Search API lets you discover insights about an image such as visually similar images shopping sources and related searches. The API can also perform text recognition identify entities ( people places things ) return other topical content for the user to explore and more. For more information see [ Visual Search Overview ] ( https:// docs. microsoft. com/ azure/ cognitive - services/ bing - visual - search/ overview ).
def visual_search( self, accept_language=None, content_type=None, user_agent=None, client_id=None, client_ip=None, location=None, market=None, safe_search=None, set_lang=None, knowledge_request=None, image=None, custom_headers=None, raw=False, **operation_config): """Visual Search API lets you discover insights about an image such as visually similar images, shopping sources, and related searches. The API can also perform text recognition, identify entities (people, places, things), return other topical content for the user to explore, and more. For more information, see [Visual Search Overview](https://docs.microsoft.com/azure/cognitive-services/bing-visual-search/overview). :param accept_language: A comma-delimited list of one or more languages to use for user interface strings. The list is in decreasing order of preference. For additional information, including expected format, see [RFC2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). This header and the [setLang](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-visual-search-api-v7-reference#setlang) query parameter are mutually exclusive; do not specify both. If you set this header, you must also specify the [cc](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-visual-search-api-v7-reference#cc) query parameter. To determine the market to return results for, Bing uses the first supported language it finds from the list and combines it with the cc parameter value. If the list does not include a supported language, Bing finds the closest language and market that supports the request or it uses an aggregated or default market for the results. To determine the market that Bing used, see the BingAPIs-Market header. Use this header and the cc query parameter only if you specify multiple languages. Otherwise, use the [mkt](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-visual-search-api-v7-reference#mkt) and [setLang](https://docs.microsoft.com/en-us/rest/api/cognitiveservices/bing-visual-search-api-v7-reference#setlang) query parameters. A user interface string is a string that's used as a label in a user interface. There are few user interface strings in the JSON response objects. Any links to Bing.com properties in the response objects apply the specified language. :type accept_language: str :param content_type: Must be set to multipart/form-data and include a boundary parameter (for example, multipart/form-data; boundary=<boundary string>). For more details, see [Content form types]( https://docs.microsoft.com/en-us/azure/cognitive-services/bing-visual-search/overview#content-form-types). :type content_type: str :param user_agent: The user agent originating the request. Bing uses the user agent to provide mobile users with an optimized experience. Although optional, you are encouraged to always specify this header. The user-agent should be the same string that any commonly used browser sends. For information about user agents, see [RFC 2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). The following are examples of user-agent strings. Windows Phone: Mozilla/5.0 (compatible; MSIE 10.0; Windows Phone 8.0; Trident/6.0; IEMobile/10.0; ARM; Touch; NOKIA; Lumia 822). Android: Mozilla / 5.0 (Linux; U; Android 2.3.5; en - us; SCH - I500 Build / GINGERBREAD) AppleWebKit / 533.1 (KHTML; like Gecko) Version / 4.0 Mobile Safari / 533.1. iPhone: Mozilla / 5.0 (iPhone; CPU iPhone OS 6_1 like Mac OS X) AppleWebKit / 536.26 (KHTML; like Gecko) Mobile / 10B142 iPhone4; 1 BingWeb / 3.03.1428.20120423. PC: Mozilla / 5.0 (Windows NT 6.3; WOW64; Trident / 7.0; Touch; rv:11.0) like Gecko. iPad: Mozilla / 5.0 (iPad; CPU OS 7_0 like Mac OS X) AppleWebKit / 537.51.1 (KHTML, like Gecko) Version / 7.0 Mobile / 11A465 Safari / 9537.53. :type user_agent: str :param client_id: Bing uses this header to provide users with consistent behavior across Bing API calls. Bing often flights new features and improvements, and it uses the client ID as a key for assigning traffic on different flights. If you do not use the same client ID for a user across multiple requests, then Bing may assign the user to multiple conflicting flights. Being assigned to multiple conflicting flights can lead to an inconsistent user experience. For example, if the second request has a different flight assignment than the first, the experience may be unexpected. Also, Bing can use the client ID to tailor web results to that client ID’s search history, providing a richer experience for the user. Bing also uses this header to help improve result rankings by analyzing the activity generated by a client ID. The relevance improvements help with better quality of results delivered by Bing APIs and in turn enables higher click-through rates for the API consumer. IMPORTANT: Although optional, you should consider this header required. Persisting the client ID across multiple requests for the same end user and device combination enables 1) the API consumer to receive a consistent user experience, and 2) higher click-through rates via better quality of results from the Bing APIs. Each user that uses your application on the device must have a unique, Bing generated client ID. If you do not include this header in the request, Bing generates an ID and returns it in the X-MSEdge-ClientID response header. The only time that you should NOT include this header in a request is the first time the user uses your app on that device. Use the client ID for each Bing API request that your app makes for this user on the device. Persist the client ID. To persist the ID in a browser app, use a persistent HTTP cookie to ensure the ID is used across all sessions. Do not use a session cookie. For other apps such as mobile apps, use the device's persistent storage to persist the ID. The next time the user uses your app on that device, get the client ID that you persisted. Bing responses may or may not include this header. If the response includes this header, capture the client ID and use it for all subsequent Bing requests for the user on that device. ATTENTION: You must ensure that this Client ID is not linkable to any authenticatable user account information. If you include the X-MSEdge-ClientID, you must not include cookies in the request. :type client_id: str :param client_ip: The IPv4 or IPv6 address of the client device. The IP address is used to discover the user's location. Bing uses the location information to determine safe search behavior. Although optional, you are encouraged to always specify this header and the X-Search-Location header. Do not obfuscate the address (for example, by changing the last octet to 0). Obfuscating the address results in the location not being anywhere near the device's actual location, which may result in Bing serving erroneous results. :type client_ip: str :param location: A semicolon-delimited list of key/value pairs that describe the client's geographical location. Bing uses the location information to determine safe search behavior and to return relevant local content. Specify the key/value pair as <key>:<value>. The following are the keys that you use to specify the user's location. lat (required): The latitude of the client's location, in degrees. The latitude must be greater than or equal to -90.0 and less than or equal to +90.0. Negative values indicate southern latitudes and positive values indicate northern latitudes. long (required): The longitude of the client's location, in degrees. The longitude must be greater than or equal to -180.0 and less than or equal to +180.0. Negative values indicate western longitudes and positive values indicate eastern longitudes. re (required): The radius, in meters, which specifies the horizontal accuracy of the coordinates. Pass the value returned by the device's location service. Typical values might be 22m for GPS/Wi-Fi, 380m for cell tower triangulation, and 18,000m for reverse IP lookup. ts (optional): The UTC UNIX timestamp of when the client was at the location. (The UNIX timestamp is the number of seconds since January 1, 1970.) head (optional): The client's relative heading or direction of travel. Specify the direction of travel as degrees from 0 through 360, counting clockwise relative to true north. Specify this key only if the sp key is nonzero. sp (optional): The horizontal velocity (speed), in meters per second, that the client device is traveling. alt (optional): The altitude of the client device, in meters. are (optional): The radius, in meters, that specifies the vertical accuracy of the coordinates. Specify this key only if you specify the alt key. Although many of the keys are optional, the more information that you provide, the more accurate the location results are. Although optional, you are encouraged to always specify the user's geographical location. Providing the location is especially important if the client's IP address does not accurately reflect the user's physical location (for example, if the client uses VPN). For optimal results, you should include this header and the X-MSEdge-ClientIP header, but at a minimum, you should include this header. :type location: str :param market: The market where the results come from. Typically, mkt is the country where the user is making the request from. However, it could be a different country if the user is not located in a country where Bing delivers results. The market must be in the form <language code>-<country code>. For example, en-US. The string is case insensitive. For a list of possible market values, see [Market Codes](https://docs.microsoft.com/en-us/azure/cognitive-services/bing-visual-search/supported-countries-markets). NOTE: If known, you are encouraged to always specify the market. Specifying the market helps Bing route the request and return an appropriate and optimal response. If you specify a market that is not listed in [Market Codes](https://docs.microsoft.com/en-us/azure/cognitive-services/bing-visual-search/supported-countries-markets), Bing uses a best fit market code based on an internal mapping that is subject to change. :type market: str :param safe_search: Filter the image results in actions with type 'VisualSearch' for adult content. The following are the possible filter values. Off: May return images with adult content. Moderate: Do not return images with adult content. Strict: Do not return images with adult content. The default is Moderate. If the request comes from a market that Bing's adult policy requires that safeSearch is set to Strict, Bing ignores the safeSearch value and uses Strict. If you use the site: filter in the knowledge request, there is the chance that the response may contain adult content regardless of what the safeSearch query parameter is set to. Use site: only if you are aware of the content on the site and your scenario supports the possibility of adult content. Possible values include: 'Off', 'Moderate', 'Strict' :type safe_search: str or ~azure.cognitiveservices.search.visualsearch.models.SafeSearch :param set_lang: The language to use for user interface strings. Specify the language using the ISO 639-1 2-letter language code. For example, the language code for English is EN. The default is EN (English). Although optional, you should always specify the language. Typically, you set setLang to the same language specified by mkt unless the user wants the user interface strings displayed in a different language. A user interface string is a string that's used as a label in a user interface. There are few user interface strings in the JSON response objects. Also, any links to Bing.com properties in the response objects apply the specified language. :type set_lang: str :param knowledge_request: The form data is a JSON object that identifies the image using an insights token or URL to the image. The object may also include an optional crop area that identifies an area of interest in the image. The insights token and URL are mutually exclusive – do not specify both. You may specify knowledgeRequest form data and image form data in the same request only if knowledgeRequest form data specifies the cropArea field only (it must not include an insights token or URL). :type knowledge_request: str :param image: The form data is an image binary. The Content-Disposition header's name parameter must be set to "image". You must specify an image binary if you do not use knowledgeRequest form data to specify the image; you may not use both forms to specify an image. You may specify knowledgeRequest form data and image form data in the same request only if knowledgeRequest form data specifies the cropArea field only (it must not include an insights token or URL). :type image: Generator :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: ImageKnowledge or ClientRawResponse if raw=true :rtype: ~azure.cognitiveservices.search.visualsearch.models.ImageKnowledge or ~msrest.pipeline.ClientRawResponse :raises: :class:`ErrorResponseException<azure.cognitiveservices.search.visualsearch.models.ErrorResponseException>` """ # Construct URL url = self.visual_search.metadata['url'] path_format_arguments = { 'Endpoint': self._serialize.url("self.config.endpoint", self.config.endpoint, 'str', skip_quote=True) } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} if market is not None: query_parameters['mkt'] = self._serialize.query("market", market, 'str') if safe_search is not None: query_parameters['safeSearch'] = self._serialize.query("safe_search", safe_search, 'str') if set_lang is not None: query_parameters['setLang'] = self._serialize.query("set_lang", set_lang, 'str') # Construct headers header_parameters = {} header_parameters['Accept'] = 'application/json' header_parameters['Content-Type'] = 'multipart/form-data' if custom_headers: header_parameters.update(custom_headers) header_parameters['X-BingApis-SDK'] = self._serialize.header("self.x_bing_apis_sdk", self.x_bing_apis_sdk, 'str') if accept_language is not None: header_parameters['Accept-Language'] = self._serialize.header("accept_language", accept_language, 'str') if content_type is not None: header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') if user_agent is not None: header_parameters['User-Agent'] = self._serialize.header("user_agent", user_agent, 'str') if client_id is not None: header_parameters['X-MSEdge-ClientID'] = self._serialize.header("client_id", client_id, 'str') if client_ip is not None: header_parameters['X-MSEdge-ClientIP'] = self._serialize.header("client_ip", client_ip, 'str') if location is not None: header_parameters['X-Search-Location'] = self._serialize.header("location", location, 'str') # Construct form data form_data_content = { 'knowledgeRequest': knowledge_request, 'image': image, } # Construct and send request request = self._client.post(url, query_parameters, header_parameters, form_content=form_data_content) response = self._client.send(request, stream=False, **operation_config) if response.status_code not in [200]: raise models.ErrorResponseException(self._deserialize, response) deserialized = None if response.status_code == 200: deserialized = self._deserialize('ImageKnowledge', response) if raw: client_raw_response = ClientRawResponse(deserialized, response) return client_raw_response return deserialized
Gets all legal agreements that user needs to accept before purchasing a domain.
def list_agreements( self, name, include_privacy=None, for_transfer=None, custom_headers=None, raw=False, **operation_config): """Gets all legal agreements that user needs to accept before purchasing a domain. Gets all legal agreements that user needs to accept before purchasing a domain. :param name: Name of the top-level domain. :type name: str :param include_privacy: If <code>true</code>, then the list of agreements will include agreements for domain privacy as well; otherwise, <code>false</code>. :type include_privacy: bool :param for_transfer: If <code>true</code>, then the list of agreements will include agreements for domain transfer as well; otherwise, <code>false</code>. :type for_transfer: bool :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 TldLegalAgreement :rtype: ~azure.mgmt.web.models.TldLegalAgreementPaged[~azure.mgmt.web.models.TldLegalAgreement] :raises: :class:`DefaultErrorResponseException<azure.mgmt.web.models.DefaultErrorResponseException>` """ agreement_option = models.TopLevelDomainAgreementOption(include_privacy=include_privacy, for_transfer=for_transfer) def internal_paging(next_link=None, raw=False): if not next_link: # Construct URL url = self.list_agreements.metadata['url'] path_format_arguments = { 'name': self._serialize.url("name", name, 'str'), 'subscriptionId': self._serialize.url("self.config.subscription_id", self.config.subscription_id, 'str') } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} query_parameters['api-version'] = self._serialize.query("self.api_version", self.api_version, 'str') else: url = next_link query_parameters = {} # Construct headers header_parameters = {} header_parameters['Accept'] = 'application/json' header_parameters['Content-Type'] = 'application/json; charset=utf-8' if self.config.generate_client_request_id: header_parameters['x-ms-client-request-id'] = str(uuid.uuid1()) if custom_headers: header_parameters.update(custom_headers) if self.config.accept_language is not None: header_parameters['accept-language'] = self._serialize.header("self.config.accept_language", self.config.accept_language, 'str') # Construct body body_content = self._serialize.body(agreement_option, 'TopLevelDomainAgreementOption') # Construct and send request request = self._client.post(url, query_parameters, header_parameters, body_content) response = self._client.send(request, stream=False, **operation_config) if response.status_code not in [200]: raise models.DefaultErrorResponseException(self._deserialize, response) return response # Deserialize response deserialized = models.TldLegalAgreementPaged(internal_paging, self._deserialize.dependencies) if raw: header_dict = {} client_raw_response = models.TldLegalAgreementPaged(internal_paging, self._deserialize.dependencies, header_dict) return client_raw_response return deserialized
Open handler connection and authenticate session.
async def open(self): """Open handler connection and authenticate session. If the handler is already open, this operation will do nothing. A handler opened with this method must be explicitly closed. It is recommended to open a handler within a context manager as opposed to calling the method directly. .. note:: This operation is not thread-safe. Example: .. literalinclude:: ../examples/async_examples/test_examples_async.py :start-after: [START open_close_sender_directly] :end-before: [END open_close_sender_directly] :language: python :dedent: 4 :caption: Explicitly open and close a Sender. """ if self.running: return self.running = True try: await self._handler.open_async(connection=self.connection) while not await self._handler.client_ready_async(): await asyncio.sleep(0.05) except Exception as e: # pylint: disable=broad-except try: await self._handle_exception(e) except: self.running = False raise